Skip to content
Advertisement

Char variable minus char variable parse to Int in java

I know this is trivial, but I can’t find the proper explication. I have the following code

str="1230"
int rez=str.charAt(3) - '0';
rez=3;

How does this parsing work?

Advertisement

Answer

As long as the character is a digit, you can get the equivalent int value by subtracting '0'. The ASCII coding for '0' is decimal 48, '1' is decimal 49, etc.

So '8' - '0' = 56 - 48 = 8;

For your number, you can parse the entire string like this (assuming all the characters are digits, otherwise the result wouldn’t make sense).

String v = "1230";
int result = 0; // starting point
for (int i = 0; i < v.length(); i++) {
    result = result* 10 + v.charAt(i) -'0';
}
System.out.println(result);

Prints

1230

Explanation

In the above loop, first time thru
result = 0 * 10 + '1'-'0 = 1
second time thru 
result = 1 * 10  + '2'-'0' = 12
third time thru 
result = 12 * 10  + '3'-'0' = 123
last time thru 
result = 123 * 10  + '0'-'0' = 1230
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement