Reverse words in a sentence - Swift

后端 未结 5 935
不知归路
不知归路 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条回答
  •  逝去的感伤
    2021-01-29 16:19

    Building on the OPs answer, if you wanted to follow English capitalization rules on the output:

    var str = "Hello playground"
    
    let result = str.split(separator: " ").enumerated().map {
        let reversed = String($0.1.reversed())
        return $0.0 == 0 ? reversed.capitalized : reversed.lowercased()
        }
        .joined(separator: " ")
    print("Rerversing letters in each word = \"" + result + "\"") // Olleh dnuorgyalp
    

    Also note that multiple spaces would mess this up, as would commas, periods, and other word/sentence delimiters.

提交回复
热议问题