Finding second occurrence of a substring in a stri

2019-01-11 11:59发布

We are given a string, say, "itiswhatitis" and a substring, say, "is". I need to find the index of 'i' when the string "is" occurs a second time in the original string.

String.indexOf("is") will return 2 in this case. I want the output to be 10 in this case.

5条回答
做自己的国王
2楼-- · 2019-01-11 12:35

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

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;
}
查看更多
Animai°情兽
3楼-- · 2019-01-11 12:37

I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()

StringUtils.ordinalIndexOf("Java Language", "a", 2)
查看更多
叛逆
4楼-- · 2019-01-11 12:45

i think a loop can be used.

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
查看更多
叛逆
5楼-- · 2019-01-11 12:50
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

查看更多
孤傲高冷的网名
6楼-- · 2019-01-11 12:57

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

str.indexOf("is", str.indexOf("is") + 1);
查看更多
登录 后发表回答