How to reverse each word in a string with Swift

1 Answer

0 votes
import Foundation

func reverseEachWord(in s: String) -> String {
    // Split the string into words
    let words = s.components(separatedBy: " ")

    // Reverse each word
    let reversedWords = words.map { String($0.reversed()) }

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

let s = "java c++ rust python c# swift"
let result = reverseEachWord(in: s)

print(result)



/*
run:

avaj ++c tsur nohtyp #c tfiws

*/

 



answered Sep 24, 2025 by avibootz
...