话不多说,直接上代码:
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; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } } } return -1; }
核心代码如上,这indexOf函数用在很多地方,String ,StringBuffer, StringBuilder类的方法是用到过。apache有的包中替换函数也是用这个函数进行子串查找。我们分析一下参数。jdk注释如下:
* @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.
这里说一下 String类, String类是对char基本类型的封装。直接上图:
就是char型数组以及一个hash。
算法很简单,将两个字符串通过字符型数组来比较,从目标字符串中查找待查找串中的第一个字符,当找到,j、k 指针自增1后移。当移动长度到 之前计算的end的长度时结束,说明找到,否则没有找到。