How to Count Occurrences in String Kotlin - Simple Guide
In Kotlin, you can count occurrences of a character or substring in a string using the
count function with a condition or by using windowed for substrings. For example, str.count { it == 'a' } counts how many times 'a' appears in str.Syntax
The main way to count occurrences of a character in a string is using the count function with a condition inside curly braces. For substrings, you can use windowed to check each part of the string.
string.count { it == 'char' }counts a single character.string.windowed(substring.length).count { it == substring }counts a substring.
kotlin
val str = "banana" val countChar = str.count { it == 'a' } val countSub = str.windowed(2).count { it == "an" }
Example
This example shows how to count the number of times the character 'a' appears and how many times the substring "an" appears in the string "banana".
kotlin
fun main() {
val str = "banana"
val countChar = str.count { it == 'a' }
val countSub = str.windowed(2).count { it == "an" }
println("Number of 'a': $countChar")
println("Number of 'an': $countSub")
}Output
Number of 'a': 3
Number of 'an': 2
Common Pitfalls
A common mistake is trying to count substrings using count directly on the string, which only works for characters. Also, overlapping substrings are not counted by default with windowed. For example, counting "ana" in "banana" requires special handling.
kotlin
fun main() {
val str = "banana"
// Wrong: counts characters, not substrings
// val wrongCount = str.count { it == 'an' } // Error: 'it' is Char, not String
// Right: use windowed for substrings
val correctCount = str.windowed(3).count { it == "ana" }
println("Count of 'ana': $correctCount")
}Output
Count of 'ana': 1
Quick Reference
| Task | Kotlin Code Example |
|---|---|
| Count character 'a' | str.count { it == 'a' } |
| Count substring "an" | str.windowed(2).count { it == "an" } |
| Count substring with length 3 "ana" | str.windowed(3).count { it == "ana" } |
Key Takeaways
Use
count with a condition to count characters in a string.Use
windowed with count to count substrings.Counting overlapping substrings requires careful use of
windowed with the correct size.Do not try to count substrings directly with
count as it works on characters.Always test your counting logic with examples to avoid off-by-one errors.