Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java indexOf method for multiple matches in String

Tags:

java

indexof

I had a question about the indexOf method. I want to find multiple cases of "X" in a string.

Suppose my string is "x is x is x is x", I want to find x in all of its index positions. But how do you do this for multiple cases? Is this even possible with indexOf?

I did int temp = str.indexOf('x'); It find the first x. I tried to do a for loop where i is initialized to length of string and this did not work since I kept finding the first x over and over.

for (int y = temp1; y >= 0;y-- )  {     int temp = str.indexOf('x');     System.out.println(temp); } 

But this does not work. Am I supposed to use regex? Because I don't really know how to use regex method.

Any help would be appreciated, thanks!

like image 644
Eric Avatar asked Feb 14 '11 01:02

Eric


People also ask

How many indexOf () methods does the string class have?

Java String indexOf() There are four variants of indexOf() method.

How do you find the index of all occurrences of an element in a string?

Using indexOf() and lastIndexOf() method The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.

Which is faster indexOf or contains Java?

Even if I switch the order of indexOf and contains, indexOf is still faster. In the benchmark i linked, the passed value is also alreday a string!

What does indexOf () Do Java?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string.


2 Answers

There is a second variant of the indexOf method, which takes a start-index as a parameter.

i = str.indexOf('x'); while(i >= 0) {      System.out.println(i);      i = str.indexOf('x', i+1); } 
like image 123
Paŭlo Ebermann Avatar answered Oct 04 '22 03:10

Paŭlo Ebermann


There's a another version of indexOf method, taking fromIndex as parameter.
So, you can call it in a loop, each time passing prevPosition + 1 as a second parameter.

Documentation:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(int, int)

like image 43
Nikita Rybak Avatar answered Oct 04 '22 02:10

Nikita Rybak