1 2 3 4
| String.indexOf(String str)
String.indexOf(String str, int fromIndex)
|
1 2 3 4
| String.lastIndexOf(String str)
String.lastIndexOf(String str, int fromIndex)
|
两个方法查找失败时均是返回 -1
疑惑:我对lastIndexOf()从指定索引处反向查找表示疑惑,如下实例
1 2 3 4 5 6
| String s1 = "9876543210123456789; System.out.println(s1.lastIndexOf("123")); //10 /* 我想从第十位开始向前查找,应该是无法找到匹配的“123”子串了,返回-1(我想错了) 实际情况,依旧返回了10。 */ System.out.println(s1.lastIndexOf("123", 10));
|
分析源码:
如图:部分源码

lastIndexOf() 源码中在指定的索引上加target长度后的位置开始反向查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| int strLastIndex = targetOffset + targetCount - 1;
char strLastChar = target[strLastIndex];
int min = sourceOffset + targetCount - 1;
int i = min + fromIndex;
eg: String s1 = "9876543210123456789; // fromIndex = 10; s1.lastIndexOf("123", 10); // 从索引10开始找 "9876543210 '1' 23456789"; // 其实会从索引10 + 2开始往前找 "987654321012 '3' 456789";
|