How to get the number of characters that two strings have in common in Swift

1 Answer

0 votes
func commonCharactersCount(_ str1: String, _ str2: String) -> Int {
    let set1 = Set(str1)
    let set2 = Set(str2)
    
    return set1.intersection(set2).count
}

let str1 = "abcdefg"
let str2 = "xayzgoe"

print(commonCharactersCount(str1, str2))



/*
run:

3

*/

 



answered Mar 20, 2025 by avibootz
...