find the shortest word in a string in swift

To find the shortest word in a string in Swift, you can first use the componentsSeparatedBy method to split the string into an array of words. Then, you can loop through the words to find the shortest one by comparing their lengths.

Here's the code:

main.swift
func shortestWord(in string: String) -> String? {
    let words = string.components(separatedBy: .whitespacesAndNewlines)
    var shortestWord: String?
    
    for word in words {
        if let shortest = shortestWord {
            if word.count < shortest.count {
                shortestWord = word
            }
        } else {
            shortestWord = word
        }
    }
    
    return shortestWord
}
413 chars
17 lines

You can call this function with a string as its argument to get the shortest word in the string. It returns an optional string, which will be nil if the input string is empty or contains no words.

Here's an example usage:

main.swift
let string = "The quick brown fox jumps over the lazy dog"
if let shortest = shortestWord(in: string) {
    print("The shortest word is \(shortest)")
} else {
    print("No words found")
}
189 chars
7 lines

This will output "The shortest word is fox".

gistlibby LogSnag