【发布时间】:2016-10-19 00:30:35
【问题描述】:
我正在尝试将 not remove 标点符号从数组中的单词中分离出来。
例如,这个数组包含带有标点符号的单词:
let words = ["hello", "world!!"]
下面的代码执行了一个标点符号的隔离。
for i in 0..<words.count {
if let range = words[i].rangeOfCharacter(from: .punctuationCharacters) {
words.insert(words[i].substring(with: range), at: i+1)
words[i].replaceSubrange(range, with: "")
}
}
因此words 数组变为:
["hello", "world!", "!"]
但是,我希望该功能可以单独隔离每个标点符号,而不是像现在这样一次一个:
["hello", "world", "!", "!"]
截至目前,我已经尝试遍历字符串的字符并针对 CharacterSet.punctuationCharacters 进行测试,但这感觉效率低且笨拙。
我怎样才能以 Swift-y 的方式实现这一点?
【问题讨论】:
标签: arrays swift swift3 punctuation