arrays - 从字符串数组中过滤掉空字符串

标签 arrays swift string

我从外部源接收到一个 json 字符串数组,我的一些字符串看起来像

"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00"

我想过滤掉所有只包含这些空值的字符串。 这个我试过了

arr = arr.filter { (str: String) -> Bool in
            let invalid = String(data: Data.init(count: str.count), encoding: String.Encoding.utf8)
            print(str)

            return str == invalid
        }

由于这些都是空终止符,我决定创建一个与 str 长度相同但只包含空终止符的空字符串并比较它们。

但这行不通。任何帮助将不胜感激。

最佳答案

我不认为那些是空终止符,因为反斜杠被转义了。这些只是重复多次的四个字符序列 \x00

要匹配这样的模式,可以使用正则表达式:

let regex = try! NSRegularExpression(pattern: "^(?:\\\\x00)+$", options: [])
let string = "\\x00\\x00\\x00\\x00\\x00"
// the below will evaluate to true if the string is full of \x00
regex.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) != nil

关于arrays - 从字符串数组中过滤掉空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51488878/

相关文章:

python - 如何在文件读取期间从每一行中去除换行符?

iphone - 检查文本字段文本是否几乎等于字符串

c# - C# for 循环和 Array.Fill 之间的性能差异

php - Pootle 导出不正确的 PHP 数组文件

ios - 使用 NSJSONSerialization.JSONObjectWithData() 解析数据但无法仅访问数组组字符串

ios - Swift 约束以编程方式创建奇怪的行为

python - 如何将一个列表的元素放入另一个列表的中间?一款一维战舰游戏。 (Python)

java - 根据字符串中的数字对字符串进行排序,Java

ios - 未显示 Collection View ,从未调用 cellForItemAtIndexPath

c++ - C++上的字符串过滤