DEV Community

Bibin Jaimon
Bibin Jaimon

Posted on • Edited on

1 1

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay