swift - 如何在 swift 中实现 remove_if(从数组中删除标点符号)?

标签 swift dictionary functional-programming

问题

假设我有一个字符串数组。

仅使用函数式编程(map、reduce 等...),我想创建一个没有任何标点符号的新数组。

假设没有嵌入标点符号(即它们将单独存在)。

let test_arr = [ "This", "is", "a", "test", ";", "try", "it", "." ]
let punc = [ "!":true, ".":true, "?":true, ";":true ]
let new_arr = test_arr.remove_if { punc[ $0 ]? != nil }  // how to implement?

也许这样的东西已经存在了?我没有在 Apple 文档中使用谷歌搜索。

最佳答案

我认为最好的办法是使用 filter() 并根据 NSCharacterSet 的 puncuationCharacterSet() 检查当前元素。这应该可以满足您的要求。

let test_arr = [ "This", "is", "a", "test", ";", "try", "it", "." ]

let charSet = NSCharacterSet.punctuationCharacterSet()
let noPuncuation = test_arr.filter { $0.rangeOfCharacterFromSet(charSet, options: .LiteralSearch, range: nil)?.startIndex == nil }

println(noPuncuation) // [This, is, a, test, try, it]

请注意,您可以使用 this answer 中的代码获取给定字符集中所有字符的列表,或像这样定义您自己的字符集。

let customCharset = NSCharacterSet(charactersInString: "!@#")

关于swift - 如何在 swift 中实现 remove_if(从数组中删除标点符号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518085/

相关文章:

Python 不可散列类型 : 'OrderedDict'

android - 通过给定的 GPS 坐标跟踪车辆应用程序

python - 检索与嵌套字典中最小值对应的键

java - Guava 中 Supplier<T> 的倒数

swift - Swift 的多维变量

ios - 如何在 iOS swift4 中更改特定的 UITableviewcell 颜色

ios - 如何在 Action 边界停止 SKAction.repeatActionForever Action ?

recursion - 计算导数时的方案 "application: not a procedure;"

list - 如何找到具有最小值的元素的索引?

ios - 如何正确获取和设置 UIView 的 UIColor?