find the kth longest word in a string in swift

To find the kth longest word in a string in Swift, we can follow these steps:

  1. Remove any punctuation or special characters from the string using CharacterSet and components(separatedBy:) method of String class.
  2. Create an array of words by splitting the string with space character using components(separatedBy:) method.
  3. Sort the array in descending order of word length using sorted(by:) method of Array class.
  4. Return the word at index k-1 from the sorted array, as the array is zero-indexed.

Here's the Swift code implementation of the above algorithm:

main.swift
func kthLongestWord(in string: String, k: Int) -> String? {
    let punctuationSet = CharacterSet.punctuationCharacters
    let cleanString = string.components(separatedBy: punctuationSet).joined()
    let words = cleanString.components(separatedBy: CharacterSet.whitespaces)
        .filter { !$0.isEmpty }
        .sorted(by: { $0.count > $1.count })
    return words.count >= k ? words[k - 1] : nil
}
404 chars
9 lines

We can test the above function with the following example:

main.swift
let string = "This is a sample string to find the kth longest word."
let k = 3
let kthLongest = kthLongestWord(in: string, k: k)
print("The \(k)th Longest word in '\(string)' is: \(kthLongest ?? "nil")")
204 chars
5 lines

The output of the above code will be:

main.swift
The 3rd Longest word in 'This is a sample string to find the kth longest word.' is: longest
92 chars
2 lines

gistlibby LogSnag