Skip to content

Instantly share code, notes, and snippets.

@amomchilov
Created January 22, 2018 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amomchilov/66738d68f9f0e9201b2662a5b0ded655 to your computer and use it in GitHub Desktop.
Save amomchilov/66738d68f9f0e9201b2662a5b0ded655 to your computer and use it in GitHub Desktop.
extension String {
func mostFrequentWord() -> String? {
return Dictionary(
grouping: self
.trimmingCharacters(in: CharacterSet.letters)
.lowercased()
.components(separatedBy: CharacterSet.whitespacesAndNewlines),
by: { $0 }
)
.max(by:) { $0.value.count < $1.value.count }?.key // `key` is word, `value` is array of word, repeated `count` times
}
}
print("Let's figure. out what the most comm$on wor!!!!d is in the sentence.".mostFrequentWord() as Any)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment