今天来解析一下String方法中的indexOf这个方法
比如:
String str="你好中国";
System.out.println(str.indexOf("中国"));
返回来的结果为2;
问题来了,这个String类indexOf这个方法是怎么实现的呢?
public int indexOf(String str) {
return indexOf(str, 0);
}
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
static int indexOf(char[] source, int sourceOffset, int sourceCount,char[] target, int targetOffset, int targetCount,int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
//获取用户第一个字符
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
//先找到第一个字符
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;// 源数组索引开始处(从找到的后一个字符开始)
int end = j + targetCount - 1;// 循环跳出条件
int k = targetOffset + 1;// 目标数组索引开始处(因为已经找到一个字符)
// s:你好中国人
// t:中国
// 那么 j = 2;s数组整个长度是5; end = 3+2-1 = 4
// 也就是说:3 < 4; 也就是只能循环一次,能把剩下的 国 遍历完成。
// 原理是:两个数组都要同时匹配下一个索引所在处的值
// 所以需要两个变量来递增索引
// 需要注意的是:j和k的起始索引不同,end既能控制循环的次数(刚好是剩下未完成的字符次数)
// 又能让源数组的索引获取到正确的值
for (; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
原理:
- 先找第一个字符,如果找到了再找后面的字符。
- 也就是 j 和 k 只要匹配就都+1,往后匹配下一对。
- 最难的就是 end,循环多少次了。j和k的起始索引不同,end既能控制循环的次数(刚好是剩下未完成的字符次数),又能让源数组的索引获取到正确的值