Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use -'0' beside charAt(i)?

Tags:

java

string

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.

like image 444
Pariya Avatar asked Sep 15 '12 14:09

Pariya


People also ask

Why do we use charAt 0?

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.

Why we are using charAt -' A?

'a' is a char literal. char is an integer type, so arithmetic with char 's is well defined and produces an integral result.

What is the use of 0 in Java?

'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).


3 Answers

Because string.charAt(i) returns char. But puz is int[].

So string.charAt(i) - '0'converts it to an integer.

like image 110
Petar Minchev Avatar answered Oct 16 '22 10:10

Petar Minchev


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');
like image 32
Sujay Avatar answered Oct 16 '22 11:10

Sujay


You're better off using Character.isDigit(char) and Character.getNumericValue(char) to test and convert a char into an integer value.

like image 2
Bobulous Avatar answered Oct 16 '22 11:10

Bobulous