Reverse words in a sentence - Swift

后端 未结 5 843
不知归路
不知归路 2021-01-29 15:43

How to perform reversing of all words in a sentence.

Example

let str = \"Hello playground\"

Result should be like \"olleH dnuorg

5条回答
  •  梦毁少年i
    2021-01-29 16:36

    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..

提交回复
热议问题