String.indexOf()和String.lastIndexOf()

1
2
3
4
// 返回指定字符串在此字符串中第一次出现的索引,不给定fromIndex参数时,源码默认会为fromIndex赋值为0
String.indexOf(String str)
// 返回指定字符串在此字符串中第一次出现的索引,从指定索引开始查找
String.indexOf(String str, int fromIndex)
1
2
3
4
// 返回指定字符串在此字符串中最右边出现的索引,不给定fromIndex参数时,源码默认会为fromIndex赋值为str的长度
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));

分析源码:

如图:部分源码

image-20220120131215816

lastIndexOf() 源码中在指定的索引上加target长度后的位置开始反向查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 子串最后一个下标
int strLastIndex = targetOffset + targetCount - 1;
// 子串中最后一个char字符
char strLastChar = target[strLastIndex];
// 被查字符串(sourceStr)需要匹配的最小索引下标,小于该值时,就没有必要继续查找了
int min = sourceOffset + targetCount - 1;
// 被查字符串(sourceStr)从第i(i = formIndex + targetCount - 1,sourceoffset这里是0)个索引开始比较子串
int i = min + fromIndex;

eg:
String s1 = "9876543210123456789;
// fromIndex = 10;
s1.lastIndexOf("123", 10);
// 从索引10开始找 "9876543210 '1' 23456789";
// 其实会从索引10 + 2开始往前找 "987654321012 '3' 456789";