Indexes of all occurrences of character in a string

Trufa picture Trufa · Feb 17, 2011 · Viewed 175.4k times · Source

The following code will print 2

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

I would like to know how to get all the indexes of "n" ("guess") in the string "bannanas"

The expected result would be: [2,3,5]

Answer

Ted Hopp picture Ted Hopp · Feb 17, 2011

This should print the list of positions without the -1 at the end that Peter Lawrey's solution has had.

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

It can also be done as a for loop:

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

[Note: if guess can be longer than a single character, then it is possible, by analyzing the guess string, to loop through word faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]