Find all occurrences of character in a Kotlin String
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:
|
1 2 3 4 5 6 7 |
fun main() { val s = "one, two, three, four, five" val c = ',' val index = s.indexOf(c) println(index) // 3 } |
Similarly, the lastIndexOf() function returns the index of the character’s “last” occurrence within a string.
|
1 2 3 4 5 6 7 |
fun main() { val s = "one, two, three, four, five" val c = ',' val lastIndex = s.lastIndexOf(c) println(lastIndex) // 16 } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val s = "one, two, three, four, five" val c = ',' var index = s.indexOf(c) while (index != -1) { println(index) index = s.indexOf(c, index + 1) } } |
Output:
3
8
15
21
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val s = "one, two, three, four, five" val c = ',' var index = -1 while (s.indexOf(c, index + 1).also { index = it } != -1) { println(index) } } |
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:
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val string = "One, Two, Three, Four, Five" val pattern = "o" val indices = Regex(pattern).findAll(string) .map { it.range.first } .toList() println(indices) // [7, 18] } |
To enable case-insensitive matching, specify the IGNORE_CASE regex option.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val string = "One, Two, Three, Four, Five" val pattern = "o" val indices = Regex(pattern, RegexOption.IGNORE_CASE).findAll(string) .map { it.range.first } .toList() println(indices) // [0, 7, 18] } |
We can handle some special inputs like overlapping characters by modifying the Regex to use positive lookahead. For example,
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val string = "aaa" val pattern = "aa" var indices = Regex(pattern).findAll(string).map { it.range.first }.toList() println(indices) // [0] indices = Regex("(?=$pattern)").findAll(string).map { it.range.first }.toList() println(indices) // [0, 1] } |
That’s all about finding indexes of all occurrences of a character or a substring in a Kotlin String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)