122 votes

Indices de toutes les occurrences d'un caractère dans une chaîne de caractères

Le code suivant imprimera 2

String word = "bannanas";
String guess = "n";
int index;
System.out.println( 
    index = word.indexOf(guess)
);

Je voudrais savoir comment obtenir tous les index de "n" ("devine") dans la chaîne "bannanas".

Le résultat attendu serait : [2,3,5]

3voto

urSus Points 2583
int index = -1;
while((index = text.indexOf("on", index + 1)) >= 0) {
   LOG.d("index=" + index);
}

2voto

hev1 Points 6033

Java 8+.

Pour trouver tous les index d'un caractère particulier dans un fichier String on peut créer un IntStream de tous les index et filter par-dessus.

import java.util.stream.Collectors;
import java.util.stream.IntStream;
//...
String word = "bannanas";
char search = 'n';
//To get List of indexes:
List<Integer> indexes = IntStream.range(0, word.length())
        .filter(i -> word.charAt(i) == search).boxed()
        .collect(Collectors.toList());
//To get array of indexes:
int[] indexes = IntStream.range(0, word.length())
        .filter(i -> word.charAt(i) == search).toArray();

1voto

asgs Points 2083
String word = "bannanas";

String guess = "n";

String temp = word;

while(temp.indexOf(guess) != -1) {
     int index = temp.indexOf(guess);
     System.out.println(index);
     temp = temp.substring(index + 1);
}

0voto

idris yıldız Points 1853
    String input = "GATATATGCG";
    String substring = "G";
    String temp = input;
    String indexOF ="";
    int tempIntex=1;

    while(temp.indexOf(substring) != -1)
    {
        int index = temp.indexOf(substring);
        indexOF +=(index+tempIntex)+" ";
        tempIntex+=(index+1);
        temp = temp.substring(index + 1);
    }
    Log.e("indexOf ","" + indexOF);

0voto

Elite Vip Points 1

Aussi, si vous voulez trouver tous les index d'une chaîne dans une chaîne.

int index = word.indexOf(guess);
while (index >= 0) {
    System.out.println(index);
    index = word.indexOf(guess, index + guess.length());
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X