1前言
不多说,直接上源码
2源码
我自己的理解,可能表述不清,多看几遍,不行就debug跟一遍代码自然就懂了。
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched. 要搜索的源字符串
* @param sourceOffset offset of the source string. 源字符串偏移量即起始位置
* @param sourceCount count of the source string. 源字符串长度
* @param target the characters being searched for. 要搜索的目标字符串
* @param targetOffset offset of the target string. 目标字符串偏移量即起始位置
* @param targetCount count of the target string. 目标字符串长度
* @param fromIndex the index to begin searching from. 开始搜索位置
*/
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. */
//找到第一个字符的位置,for循环嵌套while循环直到找到
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;
//第一个字符之后的字符是否也一一相等
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
//如果j=end则说明第一个字符之后的字符也一一相等
//否则继续循环找下一个字符
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
3后续
亮点:
1、匹配首个目标字符。for循环中,嵌套while循环,从源字符串中,找到匹配目标字符的位置。
2、小范围匹配目标字符串。for循环中,嵌套for循环,在[目标字符串]长度范围内,遍历匹配,如果全部匹配,则return。