2013-09-26 155 views
36

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

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

回答

84

使用重载版本的indexOf(),这需要起始东印度作为第二个参数:

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

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

+0

如果什么发生是两次以上? –

+1

然后没有什么特别的事情发生,它仍然需要第二次发生。 –

+0

第三次发生的指数呢! –

0

我觉得一个循环都可以使用。

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 
0

您可以编写一个函数返回的发生位置的阵列,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; 
} 
相关问题