Reputation: 25
I write a simple code and need to get each number in a string as an Integer But when I try to use Convert.ToInt32() it give me another value
Example:
string x="4567";
Console.WriteLine(x[0]);
the result will be 4 , but if i try to use Convert
Console.WriteLine(Convert.ToInt32(x[0]));
it Give me 52 !!
I try using int.TryParse() and its the same
Upvotes: 2
Views: 237
Reputation: 15167
A char
is internally a short integer
of it's ASCII
representation.
If you cast/convert (explicitly or implicitly) a char to int, you will get it's Ascii value. Example Convert.ToInt32('4')
= 52
But when you print it to Console, you are using it's ToString() method implicitly, so you are actually printing the ASCII
character '4'. Example: Console.WriteLine(x[0]) is equivalent to Console.WriteLine("4")
Try using an ASCII
letter so you will notice the difference clearly:
Console.WriteLine((char)('a')); // a
Console.WriteLine((int)('a')); // 97
Now play with char
math:
Console.WriteLine((char)('a'+5)); // f
Console.WriteLine((int)('a'+5)); // 102
Bottom line, just use int digit = int.Parse(x[0]);
Or the funny (but less secure) way: int digit = x[0] - '0';
Upvotes: 0
Reputation: 2971
you can alternatively do this way to loop through all characters in a string
foreach (char c in x)
{
Console.WriteLine(c);
}
Will Print 4,5,6,7
And as suggested in earlier answer before converting to integer make that as a sting so it doesn't return the ascii code
Upvotes: 0
Reputation: 22911
According to the docs:
The ToInt32(Char) method returns a 32-bit signed integer that represents the UTF-16 encoded code unit of the value argument. If value is not a low surrogate or a high surrogate, this return value also represents the Unicode code point of value.
In order to get 4, you'd have to convert it to a string before converting to int32:
Console.WriteLine(Convert.ToInt32(x[0].ToString()));
Upvotes: 2