Java row index with "\ n"

with this line:

String test = "hey\nyo\nsup\nyello";

and i call

System.out.println(test.indexOf("yello")); 

I get 11, how is this number produced? and "\ n" is considered a character in the string?

+4
source share
3 answers

Does "\ n" count as a character in a string?

Yes, in java it is \nconsidered as one character

h e y \n y o \n s u p \n yello
-------------------------------
0 1 2  3 4 5  6 7 8 9 10 11

That's why you got 11fortest.indexOf("yello")


You can try this as evidence:

String str = "\n";
System.out.println(str.length());

will give you 1as a day off

+7
source

Consider

"hey\nyo\nsup\nyello"
 0 0  0  0 0  1 1 1    (x)
 0 2  4  6 8  0 2 4    (y)

Where each char index in the string is (10x + y).

As you can see, y is at position 11 (and yes \n- one char)

+3
source

, \n Java.

:

"hey\nyo\nsup\nyello"
 0 0  0  0 0  1 1 1 
 0 2  4  6 8  0 2 4

, y 11. .

+2
source

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


All Articles