This article explores different ways to count occurrences of a given character in a string in Kotlin.

1. Using filter() function

The recommended solution is to use the filter() function to count occurrences of the given character in a string.

Download Code

2. Using replace

Another solution is to remove all occurrences of the specified character from the string and return the difference of its length with that of the original string.

Download Code

3. Using Regex

You can also use regular expressions to split the string based on pattern and count the matched occurrences.

Download Code

4. Using Frequency Map

If the total number of lookups is more, consider creating a frequency map to do lookups in constant line efficiently. A frequency map stores count of each distinct character present in the string.

Download Code

5. Custom Routine

Another plausible way is to write your routine for this simple task. The idea is to iterate over the characters in the string using a for-loop and increment the counter if the current character matches the specified character.

Download Code

That’s all about counting occurrences of a given character in a string in Kotlin.