I read Hello Android book and i dont understand a piece of code this function.
Why we use -'0' beside charAt(i)??
static protected int[] fromPuzzleString(String string) {
int[] puz = new int[string.length()];
for (int i = 0; i < puz.length; i++) {
puz[i] = string.charAt(i) - '0' ;
}
return puz;
}
Thanks you. Cheers.
charAt(0). This returns the first character in our string. In other words, we retrieve the character with the index value 0. In this case, the charAt() method returned the character G.
'a' is a char literal. char is an integer type, so arithmetic with char 's is well defined and produces an integral result.
'0' is the char value of zero. When you write a string, you're writing an array of 'char' datatypes which the compiler translates into ASCII values (which have a corresponding decimal number value).
Because string.charAt(i)
returns char
. But puz
is int[]
.
So string.charAt(i) - '0'
converts it to an integer.
What you're trying to do is read a char, one at a time, convert it to an int and store it in your array.
The ASCII code for 0 is 48. So what you're actually trying to do is subtract this value from the ASCII value of the char at that particular location and then store the numeric result in the corresponding index.
You can verify it for yourself, if you try to print it out in your loop, something like:
System.out.println((int)string.charAt(i));
System.out.println((int)'0');
You're better off using Character.isDigit(char)
and Character.getNumericValue(char)
to test and convert a char into an integer value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With