【问题标题】:Filter out null character strings from string array从字符串数组中过滤掉空字符串
【发布时间】:2018-07-24 00:30:19
【问题描述】:

我从外部源收到一个 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 长度相同但仅包含空终止符的空字符串并进行比较。

但这不起作用。任何帮助将不胜感激。

【问题讨论】:

  • 你确定那些是空终止符吗?好像是反斜杠字符,后跟 x,后跟 2 个零。
  • 你是对的。这些不是空终止符。不知道为什么我要为外部源获取该字符串。我想我必须弄清楚

标签: arrays swift string


【解决方案1】:

我不认为这些是空终止符,因为反斜杠被转义了。这些只是重复多次的四个字符序列\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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多