如何在不使用正则表达式的情况下检查子字符串是否重复?

How to check if a substring is repeated without using regex?

我想检查一个字符串是否包含重复的子字符串。

例如,如何在 Java 中不使用正则表达式库来检查 (bc)*

您可以简单地使用这个递归算法:

public static boolean repeatedString(String str, String repeat, int lastIndex) {
    int next = str.indexOf(repeat, lastIndex+repeat.length());

    if(next == -1) return false;
    else if(next-lastIndex == repeat.length()) return true;
    else return repeatedString(str, repeat, next);
}

调用repeatedString(str, "bc", -1),本质上是检查repeat的任意两次是否连续出现。

一种简单的方法是过滤每个字符并检查它是否以您要查找的子字符串开头。

public static int countSubstringOccurences(String st, String substring) {
    int count = 0;
    for(int i = 0; i < st.length(); i++) {
        if(st.substring(i).startsWith(substring)) {
            count++;
        }
    }
    return count;
}

此 will 方法将测试给定字符串的每个子字符串,看它是否以给定子字符串开头,并在每次找到匹配项时将计数加一。