4
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.
4
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.
4
All char is a corresponding integer of the table ASCII, and the '0' is the base value of this table, that is, all characters have a corresponding integer value and in a subtraction operation the result is the corresponding integer of this table, so it works.
References
3
According to the documentation of the C#, the char can be converted implicitly to int
(... )
charcan be converted implicitly toushort,int,uint,long,ulong,float,doubleor `decimal.
However, beware of unexpected results. A explanation by @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.
0
you must use Tostring() not to use ASC code and then Tryparse to verify that 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();
Browser other questions tagged c# char
You are not signed in. Login or sign up in order to post.