java - Indexes of all occurrences of character in a string -
the following code print 2
string word = "bannanas"; string guess = "n"; int index; system.out.println( index = word.indexof(guess) ); i know how indexes of "n" ("guess") in string "bannanas"
the expected result be: [2,3,5]
this should print list of positions without -1 @ end 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 done for loop:
for (int index = word.indexof(guess); index >= 0; index = word.indexof(guess, index + 1)) { system.out.println(index); } [note: if guess can longer single character, possible, analyzing guess string, loop through word faster above loops do. benchmark such approach boyer-moore algorithm. however, conditions favor using such approach not seem present.]
Comments
Post a Comment