arrays - 从 Swift 中的单词中分离标点符号

标签 arrays swift swift3 punctuation

我试图从数组中的单词中分离而不是删除标点符号。

例如,这个数组包含带有标点符号的单词:

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/

相关文章:

arrays - Swift 崩溃 : Array. _allocateBufferUninitialized

python - 如何将 vtkimage 转换为 numpy 数组

c - 在巨大的二维数组中找到第 N 个最大的元素

JavaScript 字符串分割 : fixed-width vs. 分隔性能

swift - Scene Kit Swift 节点多次旋转

ios - 以编程方式将自定义 View 添加到另一个 View

swift - "{ _ in }"在 Swift 中是什么意思?

c - 在 Swift 中格式化 Linphone SDK 的路径时出现问题

swift - 获取核心数据问题

swift - 从另一个类访问 DispatchGroup