Swift reverse a string word by word
Video: Swift reverse a string word by word by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift Reverse a String Word by Word
Reversing a string word by word in Swift involves splitting the string into its individual words, reversing their order, and then joining them back into a single string. This technique is useful for manipulating sentences or phrases while preserving the integrity of each word.
Code
let original = "Swift reverse a string word by word"
// Split the string into words using whitespace as the separator
let words = original.split(separator: " ")
// Reverse the array of words
let reversedWords = words.reversed()
// Join the reversed words back into a single string with spaces
let reversedString = reversedWords.joined(separator: " ")
print(reversedString) // Output: "word by word string a reverse Swift"
Key Points
- Use the split(separator:) method to divide a string into words based on spaces.
- The reversed() method returns a reversed collection of the words without modifying the original array.
- Join the reversed words with joined(separator:) to reconstruct the sentence.
- This approach preserves each word's characters while changing their order.