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.

Download Code

2. Using Pattern.compile() function

Another solution is to use regular expressions to count the substring frequency, as shown below:

Download Code

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:

Download Code

That’s all about finding the occurrences of a substring in a string in Kotlin.