jdk源码心得 indexOf()的分析

话不多说,直接搬上indexOf()系列最底层源码。

indexOf()??? -> 查找target在source里的index。

/**
 * 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) {
// 从第一行的参数列表看出,共需(1.源字符串数组  2.源。。偏移位  3.源。。个数)(4.目标字符串数组  5.目标。。偏移位 
// 6.目标 。。个数) 以及 (7.查找的索引)等七个参数。
// 查找的索引:要从source字符串中第几个开始查找是否含有target,如果有,返回这个index

// 查找需要一定的判断规则。
// 规则(一)如果查找的索引 大于等于 源字符串 字符的个数,首先判断目标字符串的个数 是否等于 0
// 如果等于 0, 则返回源字符串 字符个数;如果不等于 0,则返回 -1 表示查找不到。
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
// 规则(二)如果查找的索引 小于 0,将从 0 开始查找,也就是把fromIndex的值变为 0
    if (fromIndex < 0) {
        fromIndex = 0;
    }
// 规则(三)如果查找的索引 小于等于 源字符串 字符的个数,并且 大于等于 0 (这句话,从上下文中理解得出。)
// 这时,如果目标字符串 字符个数 等于 0, 则返回查找的索引值 fromIndex
    if (targetCount == 0) {
        return fromIndex;
    }
// 首先,获得目标字符串的第一个字符。
    char first = target[targetOffset];
// 然后在源字符串中查找,看有没有这个字符。
// 从0开始?错,要从给定的索引值fromIndex 加上 源字符串的偏移位 sourceOffset 开始
// 一直到 源字符串的字符长度 - 目标字符串的字符长度,同样得加上 偏移位 sourceOffset
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
// 如果在源字符串 第一个字符 不等于 目标字符串 第一个字符,那么从源字符串 第二个字符再判断,直到找到等于它的字符 
// 当然,肯定不是到无穷多个,而是到第 max 个为止,如果还没有找到,则退出for循环,返回 -1 
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }
// 能运行到这一步,说明在源字符串中找到了 与目标字符串中的第一个字符一样的字符。
// 接下来,就是判断下一个字符是否相等
        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
// j : 表示下一个字符,一直到end为止(end :i 加上 目标字符串的长度)
            int j = i + 1;
            int end = j + targetCount - 1;
// 判断接下来,两者的字符是否相等,如果相等,就比较下下个字符是都相等。
// 如果不等,则再判断是否是最后一个字符,如果不是,则跳出这次for循环,进行下一次for循环
// 如果最后都相等,则返回这个 i - sourceOffset,就是indexOf()的索引
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}
       

猜你喜欢

转载自blog.csdn.net/qq_34561892/article/details/81318490