Find occurrences of a substring in a string in Kotlin
This article explores different ways to count the total number of occurrences of a string in another string in Kotlin.
1. Using split() function
In Kotlin, you can use the split() function to split the string around the given substring.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun countMatches(string: String, pattern: String): Int { return string.split(pattern) .dropLastWhile { it.isEmpty() } .toTypedArray().size - 1 } fun main() { val string = "AABCCAAADCBBAADBBC" val pattern = "AA" val count = countMatches(string, pattern) println(count) // 3 } |
2. Using Pattern.compile() function
Another solution is to use regular expressions to count the substring frequency, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.regex.Pattern fun countMatches(string: String, pattern: String): Int { val matcher = Pattern.compile(pattern).matcher(string) var count = 0 while (matcher.find()) { count++ } return count } fun main() { val string = "AABCCAAADCBBAADBBC" val pattern = "AA" val count = countMatches(string, pattern) println(count) // 3 } |
3. Using indexOf() function
You can also write your custom routine solution using the indexOf() function, which returns the index within this string of the first occurrence of the specified substring. The trick is to start from the position where the last found substring ends. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
fun countMatches(string: String, pattern: String): Int { var index = 0 var count = 0 while (true) { index = string.indexOf(pattern, index) index += if (index != -1) { count++ pattern.length } else { return count } } } fun main() { val string = "AABCCAAADCBBAADBBC" val pattern = "AA" val count = countMatches(string, pattern) println(count) // 3 } |
That’s all about finding the occurrences of a substring in a string in Kotlin.
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 :)