在Java中查找字符串中子字符串的第二次出现

Finding second occurrence of a substring in a string in Java

我们给了一个字符串"itiswhatitis"和一个子字符串"is"
当字符串"is"在原始字符串中第二次出现时,我需要找到'i'的索引。

在这种情况下,String.indexOf("is")将返回2。 在这种情况下,我希望输出为10。


使用indexOf()的重载版本,该版本将起始索引(fromIndex)作为第二个参数:

1
str.indexOf("is", str.indexOf("is") + 1);


我在用:
Apache Commons Lang:StringUtils.ordinalIndexOf()

1
StringUtils.ordinalIndexOf("Java Language","a", 2)

1
2
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

此重载开始从给定索引中查找子字符串。


您可以编写一个函数以返回出现位置的数组,Java具有String.regionMatches函数,这非常方便

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

我认为可以使用循环。

1
2
3
1 - check if the last index of substring is not the end of the main string.
2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string
3 - repeat the steps in a loop