字符串搜索

java原生自带搜索

大概思想 java原生jdk中自带的字符串搜索算法

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);
        //max是遍历次数,因为是字符串查找,整体来说只需要遍历sourceLeng-targetLength
        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            //先确认第一个字符串的位置
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }
            //如果找到了就是i<max的情况
            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                //这里是已经匹配到第一个字符,所以从第二个字符开始,这里的j是source里面的位置
                int j = i + 1;
                //这里的end是匹配的索引末尾
                int end = j + targetCount - 1;
                //k是target里面的第二个字符,从第二个字符开始搜索
                //j是source中已经匹配到的第二个字符,也从第二个字符开始
                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;
    }

results matching ""

    No results matching ""