gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:59:32 25 4
gpt4 key购买 nike

我从外部源接收到一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com