How to find the most repeated character in a string with Kotlin

1 Answer

0 votes
fun getMostRepeatedChar(str: String): Char? {
    val charFrequency = mutableMapOf<Char, Int>()

    // Count the frequency of each character
    for (ch in str) {
        charFrequency[ch] = charFrequency.getOrDefault(ch, 0) + 1
    }

    // Find the character with the maximum frequency
    return charFrequency.maxByOrNull { it.value }?.key
}

fun main() {
    val s = "kotlinrustc++javascriptcphpc#";
    
    val mostRepeatedChar = getMostRepeatedChar(s)
    
    println("The most frequent character is: '$mostRepeatedChar'")
}



 
/*
run:
   
The most frequent character is: 'c'
   
*/

 



answered Nov 30, 2024 by avibootz
...