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

1 Answer

0 votes
import Foundation

func getFirstRepeatedCharacter(s: String) -> Character? {
    var charCounts: [Character: Int] = [:]

    for char in s {
        charCounts[char, default: 0] += 1
        if charCounts[char]! > 1 {
            return char
        }
    }

    return nil
}

let s = "abcdxypcbop"

if let result = getFirstRepeatedCharacter(s: s) {
    print("First repeated character: \(result)")
} else {
    print("No repeated characters")
}


 
 
/*
run:
 
First repeated character: c
 
*/

 



answered Dec 2, 2024 by avibootz

Related questions

...