String 在字符串中每隔一个单词倒转一次,标点保持快速

String 在字符串中每隔一个单词倒转一次,标点保持快速,string,substring,swift4,reverse,xcode9,String,Substring,Swift4,Reverse,Xcode9,所以我陷入了一个编码挑战,我几乎也知道答案。我想我必须使用Swift 4中的子字符串调用才能100%得到它。我想倒转字符串中的每一个单词,但忽略或保持标点符号在其原始位置(索引) 这将是预期的产出 "lets trats. And ton worry tuoba proper secnetnes." 请注意,标点符号没有反转。您不应该使用组件(分隔符:)将字符串拆分为单词。看看原因。使用枚举子字符串并传入相应的选项: func reverseString(inputString: String

所以我陷入了一个编码挑战,我几乎也知道答案。我想我必须使用Swift 4中的子字符串调用才能100%得到它。我想倒转字符串中的每一个单词,但忽略或保持标点符号在其原始位置(索引)

这将是预期的产出

"lets trats. And ton worry tuoba proper secnetnes."

请注意,标点符号没有反转。

您不应该使用
组件(分隔符:)
将字符串拆分为单词。看看原因。使用
枚举子字符串
并传入相应的选项:

func reverseString(inputString: String) -> String {
    var index = 1
    var newSentence = inputString
    inputString.enumerateSubstrings(in: inputString.startIndex..., options: .byWords) { substr, range, _, stop in
        guard let substr = substr else { return }
        if index % 2 == 0 {
            newSentence = newSentence.replacingCharacters(in: range, with: String(substr.reversed()))
        }
        index += 1
    }
    return newSentence
}

print(reverseString(inputString: "lets start. And not worry about proper sentences."))
// lets trats. And ton worry tuoba proper secnetnes.

print(reverseString(inputString: "I think, therefore I'm"))
// I kniht, therefore m'I

那么你的预期产量是多少?我不知道!非常感谢。这个解决方案似乎工作得很好,但只有当您不更改正在迭代的字符串的总长度时才可以。在这里,倒车并不能改变这一点。但是,如果你想用一个较长的单词替换每个单词,这是行不通的。
inputString
中单词的原始范围不会改变,即使您对
inputString
进行了变异。只是抬头一看!
func reverseString(inputString: String) -> String {
    var index = 1
    var newSentence = inputString
    inputString.enumerateSubstrings(in: inputString.startIndex..., options: .byWords) { substr, range, _, stop in
        guard let substr = substr else { return }
        if index % 2 == 0 {
            newSentence = newSentence.replacingCharacters(in: range, with: String(substr.reversed()))
        }
        index += 1
    }
    return newSentence
}

print(reverseString(inputString: "lets start. And not worry about proper sentences."))
// lets trats. And ton worry tuoba proper secnetnes.

print(reverseString(inputString: "I think, therefore I'm"))
// I kniht, therefore m'I