Skip to content

Find Last Repeated Character in a string

Code

func getCharCountInString(_ testText:String) {
    let dict = testText.reduce([:]) { (d, c) -> Dictionary<Character,Int> in
        var d = d
        let i = d[c] ?? 0
        d[c] = i+1
        return d
    }

    //Accending order
    print((dict.sorted{ $0.key < $1.key }).map{ "\($0)\($1)"}.joined())
    //Without Accending order
    print((dict.map{ "\($0)\($1)"}).joined())
}
Example
// Example usage
getCharCountInString(testText)
Output
a4b2c1d4e4f2r2s3w3
s3c1f2b2a4r2e4w3d4

Code

func getCharCountInString(_ testText:String) {
    var charArray = Array(testText)
    var charD = [Character:Int]()
    for i in charArray {
        if let count = charD[i] {
            charD[i] = count + 1
        } else {
            charD[i] = 1
        }
    }

    print(charD.compactMap{"\($0)\($1)"})
}
Example
// Example usage
getCharCountInString(testText)
Output
["a4", "b2", "e4", "f2", "c1", "s3", "d4", "r2", "w3"]