【发布时间】:2019-01-31 19:07:07
【问题描述】:
我正在使用 Swift。 我正在尝试将句子转换为字符串数组。我使用 map 将句号和逗号与单词分开,如下所示:
extension String {
func convertSentenceToArray()-> [String] {
var sentence = String(self)
sentence.index(of: ".").map {
sentence.remove( at: $0)
sentence.insert(".", at: $0)
sentence.insert(" ", at: $0)
}
sentence.index(of: ",").map {
sentence.remove( at: $0)
sentence.insert(",", at: $0)
sentence.insert(" ", at: $0)
}
return sentence.components(separatedBy: " ")
}
}
let thisSentenceString = "I am trying to create an array from a sentence. But I don't understand, Why isn't the last fullstop removed, from the last word."
let thisSentenceArray = thisSentenceString.convertSentenceToArray()
print(thisSentenceArray)
结果:
["I", "am", "trying", "to", "create", "an", "array", "from", "a", "sentence", ".", "But ", "I", "don\'t", "understand", ",", "Why", "isn\'t", "the", "last", "fullstop", "removed,", " from", "the", "last", "word."]
所有句号和逗号都按照我的预期处理,除了最后一个。
我不明白为什么最后一个句号仍然存在。虽然我可以找到解决此问题的方法,但我想了解我所采取的方法有什么问题。
【问题讨论】:
-
您的代码(最多)处理 one 句号和 one 逗号。
-
“removed”后没有去掉逗号
-
提示:
index(of:)正在返回一个可选项,因此您使用的是Optional.map,不是Array.map