2013-09-26 2 views
36

"itiswhatitis"과 같은 부분 문자열 (예 : "is")이 제공됩니다. "is" 문자열이 원래 문자열에서 두 번째 발생하면 'i'의 색인을 찾아야합니다.Java 문자열의 두 번째 부분 문자열 찾기

String.indexOf("is")은이 경우 2를 반환합니다. 이 경우 출력을 10으로하고 싶습니다.

답변

84

를 사용하여 오버로드 된 버전 :

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

이 오버로드는 주어진 색인에서 부분 문자열을 찾기 시작합니다. 두번째 매개 변수로 시작인데 스 소요 indexOf()

+0

어떤 경우를 그 사건은 두 번 이상입니까? –

+1

다음은 특별한 일은 일어나지 않지만 두 번째 발생은 여전히 ​​발생합니다. –

+0

제 3 회 출현의 인덱스는 어떨까요! –

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

는 자바

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