我使用两个不同的字符串来测试“\ t”的最后一个索引,但它们都返回4.我认为它应该是5和4.我检查了oracle文档,我无法理解为什么。有人可以告诉我为什么吗?谢谢!
System.out.println("abc\t\tsubdir".lastIndexOf("\t"));
System.out.println("abct\tsubdir".lastIndexOf("\t"));
让我们让索引的数量更好地理解它:
字符串1
a b c \t \t s u b d i r
0 1 2 3 4 5 6 7 8 9 10
^-----------------------------------last index of \t (for that you get 4)
字符串2
a b c t \t s u b d i r
0 1 2 3 4 5 6 7 8 9 10
^-----------------------------------last index of \t (for that you get 4)
有些特殊字符应该被\
(tab \t
,breadline \n
,引用\"
...)转义。在Java中,所以它算作一个字符,而不是2
在第一行中,最后一个选项卡位于4 a b c <tab> <tab>
在第二行中,最后一个标签位于4也是a b c t <tab>
\t
算作1个字符
这是因为\t
不算作两个字符,它是一个转义序列,只计算一个字符。
你可以在这里找到完整的转义序列表:https://docs.oracle.com/javase/tutorial/java/data/characters.html
重要的是要注意计数从零开始,'\ t'仅计为一个字符。这有时会让人感到困惑,特别是如果你忘记从零开始。
0|1|2| 3| 4
a|b|c|\t|\t
a|b|c| t|\t
计数在java中以零开始,这就是为什么first和sysout返回4.为了更好地理解我添加了第3个sysout,你可以在其中找到\ t的最后一个索引将返回零。
/**
* @author itsection
*/
public class LastIndexOf {
public static void main(String[] args) {
System.out.println("abc\t\tsubdir".lastIndexOf("\t"));
System.out.println("abct\tsubdir".lastIndexOf("\t"));
System.out.println("\tabctsubdir".lastIndexOf("\t"));
}
}// the output will be 4,4,0