Working with strings in Kotlin often involves tasks like finding the frequency of characters. This article presents three Kotlin Program to Find the Frequency of Characters in a String. Each example uses a unique approach, providing versatility in solving this common programming challenge.
Example 1: Using Map
fun main() {
val input = "hello kotlin"
val charFrequency = input.groupingBy { it }.eachCount()
println(charFrequency)
}
Output:
{h=1, e=1, l=2, o=1, =1, k=1, t=2, i=1, n=1}
In this example, we utilize the groupingBy
function along with eachCount
to create a map where characters are grouped by their occurrences in the input string. The groupingBy
function groups elements based on a key selector (in this case, the character itself), and eachCount
calculates the frequency of each element in the group.
Example 2: Using Loop and Mutable Map
fun main() {
val input = "hello kotlin"
val charFrequency = mutableMapOf<Char, Int>()
for (char in input) {
charFrequency[char] = charFrequency.getOrDefault(char, 0) + 1
}
println(charFrequency)
}
Output:
{h=1, e=1, l=2, o=1, =1, k=1, t=2, i=1, n=1}
In this example, we manually iterate through each character in the input string and maintain a mutable map (charFrequency
) to store the frequency of each character. We use getOrDefault
to handle the increment of character counts.
Example 3: Using Collections Frequency
fun main() {
val input = "hello kotlin"
val charFrequency = input.groupingBy { it }.eachCount().toList().sortedByDescending { it.second }
println(charFrequency)
}
Output:
[(l, 2), (t, 2), (h, 1), (e, 1), (o, 1), ( , 1), (k, 1), (i, 1), (n, 1)]
In this example, we combine the use of groupingBy
, eachCount
, toList
, and sortedByDescending
functions to first get the character frequencies, convert them to a list, and then sort the list based on character frequency in descending order.
These examples showcase different ways to find the frequency of characters in a string using Kotlin. Whether you prefer using map operations, manual loops with mutable maps, or a combination of collection functions, Kotlin provides flexible options for character frequency calculations. Choose the method that aligns best with your coding style and requirements.