DEV Community

Bibin Jaimon
Bibin Jaimon

Posted on • Edited on

How to create a hash for a STRING in Swift

How to create an identifier for strings having same number of characters?

Use cases:

  • Group anagram in a dictionary
  • Check the number of characters in two strings are same
func createHash(_ s: String) -> String {
    var hash = Array(repeating: 0, count: 26)

    Array(s).forEach({ char in
        let index = char.asciiValue! - Character("a").asciiValue!
        hash[Int(index)] += 1
    })

    return hash
        .map({ String($0) })
        .joined(separator: ":")
}

Enter fullscreen mode Exit fullscreen mode

input: abbca
output: a2:b2:c

Top comments (0)