// String.indexOf(String str); 最终会调用该方法 /** * 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.(从原字符数组的哪个下标开始查询) */ staticintindexOf(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; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } // 如果不完全匹配,因为外层for循环中有i++,即i+1继续匹配 // 故而该方法本质上就是字符串匹配的朴素算法 } } return -1; }