我试图从数组中的单词中分离而不是删除标点符号。
例如,这个数组包含带有标点符号的单词:
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 的方式实现这一目标?
最佳答案
我不认为有一种 Swifty 时尚的方式来做到这一点,但如果您的单词排列是一致的,您可以按照以下方式进行操作:
let words = ["hello", "world!!"]
var res: [String] = []
for word in words {
res += word.components(separatedBy: .punctuationCharacters).filter{!$0.isEmpty}
res += word.components(separatedBy: CharacterSet.punctuationCharacters.inverted).filter{!$0.isEmpty}.joined().characters.map{String($0)}
}
print(res) // ["hello", "world", "!", "!"]
关于arrays - 从 Swift 中的单词中分离标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40120174/