Larissa Lemere
Larissa Lemere

Reputation: 19

Find Positions of Multiple Occurrences of a Character in a String

If I have a string line = "XYZTGEXGXRX", line.indexOf("X"); returns the index of the first "X" that is contained in that string.

What I want to know, is what what would allow me to get the second "X", or any occurrence of "X" after that?

Upvotes: 1

Views: 3224

Answers (1)

davidgiga1993
davidgiga1993

Reputation: 2863

Answer can be found here: Java indexOf method for multiple matches in String

There is a second parameter for indexOf which sets a start parameter. This code example prints all indices of x

i = str.indexOf('x');
while(i >= 0) {
     System.out.println(i);
     i = str.indexOf('x', i+1);
}

Upvotes: 2

Related Questions