Skip to content

Instantly share code, notes, and snippets.

@isisnaomi
Created January 21, 2020 18:18
Show Gist options
  • Save isisnaomi/28c54dc8ed8b86fd40345847ea165d45 to your computer and use it in GitHub Desktop.
Save isisnaomi/28c54dc8ed8b86fd40345847ea165d45 to your computer and use it in GitHub Desktop.
LongestWord
//Longest Word
//
//**Challenge**
//
//Have the function LongestWord(**sen**) take the **sen** parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume **sen** will not be empty.
//
//**Sample Test Cases**
//
//Input:"fun&!! time"
//
//Output:"time"
//
//Input:"I love dogs"
//
//Output:"love"
func longestWord(_ s: String) -> String {
let sentence = s.components(separatedBy: " ")
var longestWordFound = ""
for word in sentence {
let range = NSRange(location: 0, length: word.utf16.count)
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z]+$")
if regex.firstMatch(in: word, options: [], range: range) != nil {
if word.count > longestWordFound.count {
longestWordFound = word
}
}
}
return longestWordFound
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment