Write a Kotlin Program to Find the Frequency of Character in a String

In Kotlin, finding the frequency of characters in a string can be easily done by using a map to store the characters as keys and their corresponding frequency as values.

Here’s a Kotlin program that does just that:

fun main() {
    val str = "Hello, world!"
    val freqMap = mutableMapOf<Char, Int>()

    for (c in str) {
        if (c in freqMap) {
            freqMap[c] = freqMap[c]!! + 1
        } else {
            freqMap[c] = 1
        }
    }

    for ((key, value) in freqMap) {
        println("$key: $value")
    }
}

In this program, we first initialize the input string str and an empty mutable map freqMap that will hold the frequency of characters.

Then, we loop through each character c in the string str. We check if the character is already in the freqMap.

If it is, we increment its frequency by 1. If it’s not, we add it to the map with a frequency of 1.

Finally, we loop through the map and print out each key-value pair, which represents the character and its frequency in the string.

That’s all there is to it! This program provides a simple and efficient way to find the frequency of characters in a string in Kotlin.