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

1 Answer

0 votes
import Foundation

func getMostRepeatedChar(in string: String) -> Character? {
    guard !string.isEmpty else { return nil }

    var frequencyDict: [Character: Int] = [:]

    // Count the frequency of each character
    for char in string {
        frequencyDict[char, default: 0] += 1
    }

    // Find the character with the highest frequency
    let mostFrequentChar = frequencyDict.max { a, b in a.value < b.value }?.key

    return mostFrequentChar
}

let s = "swiftc++javascriptcphpc#"

if let mostRepeatedChar = getMostRepeatedChar(in: s) {
    print("The most frequent character is '\(mostRepeatedChar)'")
} else {
    print("The string is empty.")
}




/*
run:

The most frequent character is 'c'

*/

 



answered Nov 30, 2024 by avibootz

Related questions

...