Count occurrences of a given character in a string in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 |
fun countOccurrences(s: String, ch: Char): Int { return s.filter { it == ch }.count() } fun main() { val s = "Eeny, meeny, miny, moe" println(countOccurrences(s, 'e')) // 4 } |
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.
|
1 2 3 4 5 6 7 8 9 |
fun countOccurrences(s: String, ch: Char): Int { return s.length - s.replace(ch.toString(), "").length } fun main() { val s = "Eeny, meeny, miny, moe" println(countOccurrences(s, 'e')) // 4 } |
3. Using Regex
You can also use regular expressions to split the string based on pattern and count the matched occurrences.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.regex.Pattern fun countOccurrences(s: String, ch: Char): Int { val matcher = Pattern.compile(ch.toString()).matcher(s) var counter = 0 while (matcher.find()) { counter++ } return counter } fun main() { val s = "Eeny, meeny, miny, moe" println(countOccurrences(s, 'e')) // 4 } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun getFreqMap(chars: String): Map<Char, Int> { val freq: MutableMap<Char, Int> = HashMap() for (c in chars) { freq.putIfAbsent(c, 0) freq[c] = freq[c]!! + 1 } return freq } fun main() { val s = "Eeny, meeny, miny, moe" val ch = 'e' val freq = getFreqMap(s)[ch] println(freq) // 4 } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun countOccurrences(s: String, ch: Char): Int { var counter = 0 for (c in s) { if (c == ch) { counter++ } } return counter } fun main() { val s = "Eeny, meeny, miny, moe" println(countOccurrences(s, 'e')) // 4 } |
That’s all about counting occurrences of a given character 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 :)