This article explores different ways to find indexes of all occurrences of a character or a substring in a Kotlin String.

1. Find all indexes of a character

The indexOf() function only returns the index of the “first” occurrence of a character within the string, as demonstrated below:

Download Code

 
Similarly, the lastIndexOf() function returns the index of the character’s “last” occurrence within a string.

Download Code

 
To find the index of all instances of a character in a string, efficiently call the indexOf() function repeatedly within a loop. Note that the search for the next index starts from the previous index.

Download Code

Output:

3
8
15
21

 
This is equivalent to:

Download Code

Output:

3
8
15
21

2. Find all indexes of a substring

We can use a RegEx to find the indexes of all appearances of a “substring” in a String. A typical implementation of this approach would look like:

Download Code

 
To enable case-insensitive matching, specify the IGNORE_CASE regex option.

Download Code

 
We can handle some special inputs like overlapping characters by modifying the Regex to use positive lookahead. For example,

Download Code

That’s all about finding indexes of all occurrences of a character or a substring in a Kotlin String.