所以我陷入了编码挑战,我几乎也知道了答案。而且我认为我必须在Swift 4中使用subString调用来获得它100%。我想要反转字符串中的每个OTHER字,但忽略或保留标点符号在其原始位置(索引)。
var sample = "lets start. And not worry about proper sentences."
func reverseString(inputString: String) -> String {
let oldSentence = sample.components(separatedBy: " ")
var newSentence = ""
for index in 0...oldSentence.count - 1 {
let word = oldSentence[index]
if newSentence != "" {
newSentence += " "
}
if index % 2 == 1 {
let reverseWord = String(word.reversed())
newSentence += reverseWord
} else {
newSentence += word
}
}
return newSentence
}
reverseString(inputString: sample)
这将是预期的输出。
"lets trats. And ton worry tuoba proper secnetnes."
注意标点符号没有反转。
答案 0 :(得分:0)
您不应该使用components(separatedBy: )
在字词中分割字符串。请参阅this article了解原因。使用enumerateSubstrings
并传入相应的选项:
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