java - 不同的 JRE 使用什么子串搜索算法?

标签 java algorithm string substring

java.lang.String JavaDoc 没有说明默认的 indexOf(String) 子字符串搜索算法。所以我的问题是 - 不同的 JRE 使用哪些子字符串算法?

最佳答案

JDK 中有 src.zip 显示了实现:

/**
 * 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) {
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;
}

关于java - 不同的 JRE 使用什么子串搜索算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5830189/

相关文章:

c# - 洪水填充算法无限循环

java - react native : error: cannot find symbol after upgrade

java - 在java中更改目录所有者

java - 访问jar依赖的getResourceAsStream()

algorithm - 获取总和最大的子矩阵?

algorithm - 树排序 : time complexity

c++ - 如何获得 std::string 的准确长度?

ios - 如何在iOS中获取两个已知子字符串之间的子字符串?

java - 每秒 100 万次远程函数调用

regex - 匹配正则表达式中的单个反斜杠