在Java中查找string中第二次出现的子string

给我们一个string,比如说"itiswhatitis"和一个子string,比如说"is" 。 当string"is"在原始string中第二次出现时,我需要find'i'的索引。

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

使用indexOf()重载版本,它将开始的indes作为第二个参数:

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

这个重载开始寻找来自给定索引的子串。

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

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

我认为可以使用循环。

 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 

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

 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; }