Reading a blog article, I came across the following syntax for converting char to integer:
string value = "123";
foreach (var c in value)
{
if (char.IsDigit(c))
{
int digito = c - '0';
}
}
I wonder why this conversion works.
Reading a blog article, I came across the following syntax for converting char to integer:
string value = "123";
foreach (var c in value)
{
if (char.IsDigit(c))
{
int digito = c - '0';
}
}
I wonder why this conversion works.
All char
is a corresponding integer of the ASCII
table, and '0'
is the base value of that table, ie all characters have a corresponding integer value and in a subtraction operation the result is the corresponding integer of that table, so it works.
According to the documentation from C #, char
can be implicitly converted to int
(...)
char
can be implicitly converted toushort
,int
,uint
,long
,ulong
,float
,double
or 'decimal. >
However, beware of unexpected results. The explanation of @VirgilioNovic justifies why operations like this:
char op1 = '3';
char op2 = '1';
Console.WriteLine("Resultado: " + (op1 + op2).ToString());
Does not result in 4:
'Resultado: 100'
Because (int)op1
is 51
and (int)op2
is 49
.
You should use ToString () to not use the ASC code and then TryParse to check if it is integer.
string value = "123";
foreach (var c in value)
{
short digito;
if(Int16.TryParse(c.ToString(),out digito))
{
Console.WriteLine(digito);
}
}
Console.ReadKey();