2013-09-26 12 views

risposta

84

Uso versione di overload di indexOf(), che prende le Indes a partire come secondo parametro:

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

Questo sovraccarico inizia a cercare la sottostringa dall'indice specificato.

+0

che cosa se l'occorrenza è più di due volte? –

+1

Quindi non succede nulla di speciale, ci vorrà ancora la seconda occorrenza. –

+0

che dire dell'indice di terza occorrenza! –

0

Penso che un ciclo può essere utilizzato.

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

È possibile scrivere una funzione per restituire serie di posizioni di occorrenza, Java ha la funzione String.regionMatches che è piuttosto comodo

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