java 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);
} //source 字符串value sourceOffset 0 sourceCount 字符串length target 查询条件value //targetOffset 0 targetCount 查询条件长度 fromIndex 下表 static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
         
  //如果查询下表大于等于字符串长度  //如果查询条件长度==0就是""返回字符串长度等同于length() //如果有查询条件返回-1
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    } //没有查询坐标就是0
    if (fromIndex < 0) {
        fromIndex = 0;
    } //如果没有查询条件返回下标
    if (targetCount == 0) {
        return fromIndex;
    }
//字符数组 总是返回第一个 
    char first = target[targetOffset]; //int max = 0 +(总长度-查询条件的长度)
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {//判断查询条件条件在不在source中以便循环
            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;//直接返回-1
}
经验分享 程序员 微信小程序 职场和发展