Java.charAt (i) comparison problem

Why, when comparing char with another, should it be taken also from a string? For instance:

This does not work

   while(i < t.length() && zeroCount < 5) {
        if(t.charAt(i) == 0){
            zeroCount++;
        }
        i++;
    }

And it doesn’t

char zero = 0;

      while(i < t.length() && zeroCount < 5) {
            if(t.charAt(i) == zero){
                zeroCount++;
            }
            i++;
        }

The only way I managed to get it to work is like this ...

String zeros = "0000000000";

      while(i < t.length() && zeroCount < 5) {
            if(t.charAt(i) == zeros.charAt(i)){
                zeroCount++;
            }
            i++;
        }

Can someone explain if I am doing something wrong, or if it is simply unacceptable to do this, as the two best examples. If so, why?

+3
source share
6 answers

You are misleading

char zero = 0;

with

char zero = '0';

The former is the null character (ASCII value equal to zero), while the latter is the character representing the digit zero.

C, char , .

+10

"0"? '0', 0.

+4

Unicode 0 (aka U + 0000, "null" ) - , Unicode, 0.

'0' 0:

while(i < t.length() && zeroCount < 5) {
    if(t.charAt(i) == '0'){
        zeroCount++;
    }
    i++;
}
+4

'0' 0.

+3

, 0 '0', ASCII 48 (IIRC).

char charAt(i) == '0' char charAt(i) - '0' == 0

+3

, , . chatAt! codePointAt.

Similarly, you should not blindly use i++to iterate over a string. You should see if you can s.codePointAt(i) > Character.MAX_VALUEknow if you need to give an extra i++kicker.

For example, to print all code points in String sthe standard notation "U +":

private static void say_U_contents(String s) { 
    System.out.print("U+");
    for (int i = 0; i < s.length(); i++) {
        System.out.printf("%X", s.codePointAt(i));
        if (s.codePointAt(i) > Character.MAX_VALUE) { i++; }  // UG!
        if (i+1 < s.length()) { System.out.printf("."); }
    }
}

This way you can output both U+61.DF, U+3C3and U+1F4A9.1F4A9for the corresponding lines. This last one looks like "\uD83D\uDCA9\uD83D\uDCA9"that is just crazy.

+3
source

Source: https://habr.com/ru/post/1774712/


All Articles