Getting different values from convert char to integer - c#

when I display the 'i' variable, which would be a char value
{
class Program {
static void Main(string[] args) {
var max = 0;
var lista = new char[] {
'1',
'2',
'3',
'4'
};
foreach(char i in lista) {
Console.WriteLine(i);
/* var hola = Convert.ToInt32(i);
Console.WriteLine(hola);*/
}
}
}
}
I get this:
> 1 2 3 4
However, when converting 'i' into an int
var max = 0;
var lista = new char[] {
'1',
'2',
'3',
'4'
};
foreach(char i in lista) {
var hola = Convert.ToInt32(i);
Console.WriteLine(hola);
}
I get this:
49 50 51 52
Any idea what could be the problem? I'd like to obtain the same values, so I can evaluate them as integers and obtain the biggest of them, but I can't.

When you convert a char to an int, you get the ASCII value of that character. The neat thing with these values is that they are sequential, so if you subtract the value of '0' (the 0 character), you can convert a character representing a digit to that digit:
var hola = i - '0';

If you want the literal character and not the ascii number of the character, use the ToString() method
var hola = Convert.ToInt32(i.ToString());

WriteLine method internally converts the parameters string. Thus you can have the value you want. ToInt method return the ASCII value of that char. You have to convert your i value to string i.ToString() or you can simply substract 48 from the converted value.

Related

How do I add integers to char[] array?

So I have to write a code that picks our random numbers from 1 to 100 and add them to a char[] array. But I'm having some difficulty doing so as I can only add the numbers to the array if I convert them to a char using (char) which changes the number. Can someone please help me?
Thanks,
public char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 101));
}
return l;
}
use ToChar() method of Convert class.
Convert.ToChar(new Random().Next(1, 101))
You cannot convert an integer larger then 9 into a char because it's considered as 2 chars, i.e. 10 will be considered as 1 and 0.
so I would recommend adding it to an array of strings
(except if your trying to get a random charcode which I dont think is the case, because why till 100?)
Personally, I'd use an int[] array instead
There shouldn't be any problem in storing ints up to 65535 in a char but you will have to cast it back to an int if you don't want it to be weird:
public static void Main()
{
var x = CreationListe(200);
foreach(var c in x)
Console.WriteLine((int)c); //need to cast to int!
}
public static char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 65536));
}
return l;
}
https://dotnetfiddle.net/z5yoBn
If you don't cast it back to int, then you'll get the char at that character index in the unicode table. If you've put 65 into a char, you'll get A when you print it, for example. This is because A is at position 65 in the table:
(ASCII table image posted for brevity's sake)

Getting the sum of all numbers in a character array

I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.
I am new to coding. My apologies for any inconvienence.
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += (sep[i]);
}
Console.WriteLine(sum);
Console.ReadLine();
}
You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.
int value;
for (int i = 0; i < sep.Length; i++)
{
if (int.TryParse (sep[i].ToString(),out value))
sum += value;
}
If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.
Try this code instead:
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += int.Parse(sep[i].ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
Just for fun here is a LINQ solution.
var sum = num.Select( c => int.Parse((string)c) ).Sum();
This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.
The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."
Then we call Sum() to convert the resulting list of integers into a numeric sum.

the program should translate numbers into letters. How to?

My code should translate letters into numbers. How to translate numbers into letters?
string strs = Console.ReadLine();
Dictionary<char, int> dic = new Dictionary<char, int>
{
{'A', 1},
{'B', 2},
{'C', 3},
};
for (int i = 0; i < strs.Length; i++)
{
int val = 0;
if (dic.TryGetValue(strs[i], out val))
strs = strs.Replace(strs[i].ToString(), val.ToString());
}
Console.WriteLine(strs);
You actually do not need to use a dictionary for this. It can be done relatively easily just using the char type and the int type. Note that this assumes your example always uses upper-case characters from A-Z. If you need something more robust than this, you'll obviously need more complex logic.
public static class Converter
{
public static int? ConvertToInt(char value, char lowerLimit, char upperLimit)
{
// If the value provided is outside acceptable ranges, then just return
// null. Note the int? signature - nullable integer. You could also swap
// this with 0.
if (value < lowerLimit || value > upperLimit)
return null;
// 'A' is 65. Substracting 64 gives us 1.
return ((int)value) - 64;
}
public static char? ConvertToChar(int value, int lowerLimit, int upperLimit)
{
// Basically the same as above, but with char? instead of int?
if (value < lowerLimit || value > upperLimit)
return null;
// 'A' is 65. Substracting 64 gives us 1.
return ((char)value) + 64;
}
}
Usage would look something like this:
// = 1
int? a = Converter.ConvertToInt('A', 'A', 'F');
char? A = Converter.ConvertToChar(a, 1, (int)('F' - 'A'));
Note that you would need to do some level of string indexing, but this gives you a nice structure in that you don't need to store any state anywhere - you can just make it part of your method invocation.
All characters are in a computer mapped to a numeric value. So to get the numeric value of a character you can do the following:
int valueOfA= 'A';
Turns out that it is 65. So the following will work:
var text = "ABBA";
foreach (var character in text.ToCharArray())
{
int result=character;
Console.WriteLine(result-64);
}
for lowercase it is 33. So if you need to handle all a's as 1 then you can use:
var text = "aBBA".ToUpper();
foreach (var character in text.ToCharArray())
{
int result=character;
Console.WriteLine(result-64);
}
otherwise you need to do some checks.
Also notice that the character for 1 is not necessarily the value of 1. (in fact it is -15)

Convert a Letter to its alphabet numerical Rank

I am trying to convert a letter to its alphabet numerical order for example if I have an 'A' it will give me 00 or a 'C' 02
How can I code this in c# ?
EDIT : This is what I tried
I created this class :
public class AlphabetLetter
{
public char Letter {get; set;}
public int Rank {get; set;}
}
Those Two Lists :
public List<char> Letters = new List<char> {
'a' ,'b' ,'c' ,'d' ,'e', 'f' ,'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm',
'n' ,'o' ,'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
public List<int> Ranks = new List<int> {
00,01,02,04,05,06,07,08,09,10,11,12,13,
14,15,16,17,18,19,20,21,22,23,24,25
};
public List<AlphabetLetter> Alphabet = new List<AlphabetLetter>( );
I created the Alphabet in my Constructor :
for (int i = 0; i < 25; i++)
{
Alphabet.Add(new AlphabetLetter { Rank = Ranks[i], Letter = Letters[i] });
And tried to match a char with this function :
public int Numberize(char Letter)
{
if (Letter != null)
{
foreach (AlphabetLetter _letter in Alphabet)
{
if (Letter == _letter.Letter)
{
return _letter.Rank;
}
else
{
return 896;
}
}
}
else {
return 999;
}
}
}
But this method is not working and is too tedious.
Any suggestions?
You start by simply getting its Unicode value:
int charValue = Convert.ToInt32('A');
Then account for where 'A' is on the Unicode table (65)
int rank = charValue - 65;
Note that this won't work for lower case letters, as they are in a different position. You could use ToLower or ToUpper on the string version of the character to nullify this (as in the other answer).
string yourLetter = "C";
int i = yourLetter.ToLower().ToCharArray()[0] - 'a';
This returns 2.
An explanation: The characters as char's are in sequential order. However, there are two sequences - of uppercase, and of lowercase. So first we convert it to lowercase.
Then change it to a character (by using the built in method for turning a string into a character array, and then taking the first and only one).
Then, using the fact that c# will happily treat the char as a number, subtract the first of the sequence from it.
You do not need any fancy conversion. Just subtract ascii A and add 1.
using System;
using System.IO;
public class P{
public static void Main(string[] args) {
var letter = 'C';
Console.WriteLine(letter - 'A' + 1);
}
}
If you want to pad with leading zeroes, use ToString with a format.
Console.WriteLine((letter - 'A' + 1).ToString("00"));

Convert letter from textBox to an integer

How do I convert alphabet letter from textBox to an integer?
For example, if the user inputs "B" in the textBox, I am trying to convert B to the number 1
string a = textBox1.Text
int number = 1;
number = int.Parsed (a);
messageBox.Show(number.ToString());
Your first task is to capture only the first character from the input:
string str = textBox1.Text;
char chr = str[0]; // get first character
Now the character can be directly converted to an integer, for example:
int number = (int)chr;
However, the character 'A' is actually represented by the number 65, 'B' 66, and so on (see ASCII), so you'll have to subtract that from your input to get the intended value:
int value = number - 65;
Or if you prefer:
int value = number - (int)'A';
Now you might want to normalize input so a character 'a' will be treated as 'A', so in the end it would look a bit like this:
string str = textBox1.Text.ToUpperCase();
char chr = str[0];
int number = (int)chr;
int value = number - 65;
MessageBox.Show(value.ToString());

Categories

Resources