2013-09-26 10 views

Odpowiedz

84

Zastosowanie przeciążony wersja indexOf(), który przyjmuje Indes rozpoczynających się 2 parametru:

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

To przeciążenie rozpoczyna wyszukiwanie podciągu od danego indeksu.

+0

nuż zdarzenie jest więcej niż dwa razy? –

+1

Wtedy nic specjalnego się nie dzieje, to jeszcze zajmie drugie zdarzenie. –

+0

co z indeksem trzeciego wystąpienia! –

0

i że pętla może być używany.

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

Można napisać funkcję powrotu wachlarz stanowisk występowania, Java ma String.regionMatches funkcję, która jest dość poręczny

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; 
} 
Powiązane problemy