用这个字符串:
String test = "hey\nyo\nsup\nyello";
我打电话
System.out.println(test.indexOf("yello"));
我得到 11,这个数字是如何产生的? “\n”算作字符串中的一个字符吗?
最佳答案
“\n”算作字符串中的一个字符吗?
是的,在 java 中 \n
被视为单个字符
h e y \n y o \n s u p \n yello
-------------------------------
0 1 2 3 4 5 6 7 8 9 10 11
这就是为什么 test.indexOf("yello")
得到 11
的原因
你可以试试这个作为证明:
String str = "\n";
System.out.println(str.length());
会给你 1
作为输出
关于带有 "\n"的 Java 字符串索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21926996/