How to perform reversing of all words in a sentence.
Example
let str = \"Hello playground\"
Result should be like \"olleH dnuorg
You can use String
method enumerateSubstrings
using .byWords
options and replace the subrange of each word with the substring reversed. Note that this way the punctuation will remain in place:
import Foundation
Mutating approach:
var str = "Hello, playground!!!"
str.enumerateSubstrings(in: str.startIndex..., options: .byWords) { _, range, _, _ in
str.replaceSubrange(range, with: str[range].reversed())
}
print(str) // "olleH, dnuorgyalp!!!"
Non mutating:
let str = "Hello, playground!!!"
var result = ""
str.enumerateSubstrings(in: str.startIndex..., options: .byWords) { string, range, enclosingRange, _ in
result.append(contentsOf: string!.reversed())
result.append(contentsOf: str[range.upperBound..