How to sort the words in a string with Swift

1 Answer

0 votes
// Function to sort the words in a string
func sortWordsInString(_ s: String) -> String {
    // Create an array to hold the words
    let words = s.split(separator: " ")   // Words are separated by spaces

    // Enable automatic alphabetical sorting
    let sorted = words.sorted()

    // Optional: ignore duplicate words
    // (Swift's `uniqued()` is not built-in, so we use Set then sort again)
    let unique = Array(Set(sorted)).sorted()

    // Join the sorted words back into a single string
    return unique.joined(separator: " ")
}

// Test the function
print(sortWordsInString("the quick brown fox jumps over the lazy dog"))



/*
run:

brown dog fox jumps lazy over quick the

*/

 



answered 1 day ago by avibootz
...