This post will discuss how to find indexes of all occurrences of a character in a string in Java.

1. 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.

Download  Run Code

 
To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop. The following example demonstrates how to use the indexOf() method efficiently, where the search for the next index starts from the previous index.

Download  Run Code

Output:

1
6
12
16

 
Or even shorter:

Download  Run Code

Output:

1
6
12
16

 
If you just need the index of the character’s last appearance in a string, use the lastIndexOf() method.

Download  Run Code

2. Using IntStream.iterate() method

With Java 9, you can use the IntStream.iterate(seed, hasNext, next) method which returns a sequential ordered IntStream produced by application of the next function to an initial element seed, conditioned on satisfying the hasNext predicate. Following is a simple example demonstrating usage of this:

Download  Run Code

Output:

[1, 6, 12, 16]

3. Using Regex

To get the indexes of all appearances of a character in a String, you can also use a regex. The idea is to create a matcher to match the string for the specified character. Here’s how the code would look like:

Download  Run Code

Output:

1
6
12
16

That’s all about finding indexes of all occurrences of a character in a string in Java.