【问题标题】:I'm trying to remove backslash from string but if I print out with print I get the correct string , but if I print it with "po" I get the same string我正在尝试从字符串中删除反斜杠,但如果我用 print 打印出来,我会得到正确的字符串,但如果我用“po”打印它,我会得到相同的字符串
【发布时间】:2021-05-05 16:06:10
【问题描述】:
MyString = "CfegoAsZEM/sP\u{10}\u{10}}"
MyString.replacingOccurrences(of: "\"", with: "")

使用 print(MyString) 我得到了这个:"CfegoAsZEM/sP"(这就是我需要的) 使用 po MyString(在调试器上):"CfegoAsZEM/sP\u{10}\u{10}}"

【问题讨论】:

    标签: ios swift objective-c xcode


    【解决方案1】:

    \u{10} 是换行符

    也许更好的方法是 trim 字符串,它会删除字符串开头和结尾的所有空格和换行符

    let myString = "CfegoAsZEM/sP\u{10}\u{10}"
    let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
    

    【讨论】:

    • 感谢您的帮助,但仍然只能使用 print()
    • 我也试过这个,我得到了相同的结果 extension String { var unescaped: String { let entity = ["\0", "\t", "\n", "\r" , "\"", "\'", "\\"] var current = self 对于实体​​中的实体 { let descriptionCharacters = entity.debugDescription.dropFirst().dropLast() let description = String(descriptionCharacters) current = current. replaceOccurrences(of: description, with: entity) } return current } }
    • 很难判断包含 Unicode 标记 (\u{something}) 的字符串,因为不同环境下的外观可能不同。考虑换行符将光标移至新行,并且在打印时可能会忽略换行符。
    • 我猜你是对的,但你知道如何删除它吗?
    【解决方案2】:

    您的字符串不包含文字反斜杠字符。相反,\u{} 序列是一个转义序列,它引入了 Unicode 字符。这就是您无法使用 replacingOccurrences 删除它的原因。

    在这种情况下,正如 Vadian 指出的那样,它是“新行”字符 (0x10)。由于这是一个不可见的“空白”字符,当您使用print 字符串时您看不到它,但是当您使用po 时您会看到它。调试器向您显示不可打印字符的转义序列。如果你print(MyString.debugDescription)

    ,你也会看到序列

    很遗憾,trimmingCharactersIn 函数似乎没有考虑 Unicode 序列。

    我们可以使用filter 函数来检查字符串中的每个字符。如果字符是 ASCII 并且具有大于 31 的值(32 是空格字符,ASCII 序列中的第一个“可打印”字符),我们可以包含它。我们还需要确保包含非 ASCII 值,以免剥离可打印的 Unicode 字符(例如表情符号或非拉丁字符)。

    let MyString = "CfegoAsZEM/sP\u{10}\u{13}$}?\u{1F600}".filter { $0.asciiValue ?? 32 > 31 }
    print(MyString.debugDescription)
    print(MyString)
    

    输出

    “CfegoAsZEM/sP}??”

    CfegoAsZEM/sP}??

    asciiValue 返回一个可选值,如果字符不是纯 ASCII,则为 nil。在这种情况下,我使用了一个 nil-coalescing 运算符返回 32,这样就不会过滤字符。

    我修改了初始字符串以包含一些可打印的 Unicode,以证明它没有被过滤器剥离。

    【讨论】:

    • 是的,你是对的,它对我有用,谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2023-02-03
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多