问题
假设我有一个字符串数组。
仅使用函数式编程(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/