Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
The String is a basic data type in a programming language. Therefore, it’s important to know the basic operations and typical use cases for a String. In this tutorial, we’ll see various methods of counting occurrences of a specific character in a String.
A String is a sequence of characters. Thanks to that, we can use the string extension function to count occurrences of a single character. The count() function returns the number of characters matching the given predicate:
val string = "hello world, baeldung"
assertEquals(2, string.count { it == 'e' })
The easiest way to obtain occurrences of character is to iterate over the characters in the string using a for-loop. Then, we can increment the counter if the current character matches the specified character:
val string = "hello world, baeldung"
var counter = 0
for (c in string) {
if (c == 'e') {
counter++
}
}
assertEquals(2, counter)
Another way to count occurrences is using the replace() extension function. Firstly, we can remove all occurrences of the specified character from the string using the replace() function. As a result, it returns a new string without the character we replaced. Further, we can calculate the difference between the new string length and that of the original string. The result will be the number of occurrences of the specified character. Let’s see an example:
val string = "hello world, baeldung"
val count = string.length - string.replace("e", "").length
assertEquals(2, count)
Another method to count occurrences is to use regular expressions. We can compile our character as a regular expression, and then, we create a matcher and count the matched occurrences:
val string = "hello world, baeldung"
val matcher = Pattern.compile("e").matcher(string)
var counter = 0
while (matcher.find()) {
counter++
}
assertEquals(2, counter)
Let’s try to count occurrences using map collection. Firstly, we can store the count of each distinct character present in the string by iterating over it. The keys in the map are characters from the string, so we can easily access occurrences values by a specific character:
val string = "hello world, baeldung"
val occurrencesMap = mutableMapOf<Char, Int>()
for (c in string) {
occurrencesMap.putIfAbsent(c, 0)
occurrencesMap[c] = occurrencesMap[c]!! + 1
}
assertEquals(2, occurrencesMap['e'])