【问题标题】:How do you decode utf8-literals like "\xc3\xa6" in Swift 5?你如何在 Swift 5 中解码像 "\xc3\xa6" 这样的 utf8-literals?
【发布时间】:2021-12-30 04:27:25
【问题描述】:

我正在从蓝牙特征中获取 WiFi SSID 列表。每个 SSID 都表示为一个字符串,有些具有这些 UTF8 文字,例如“\xc3\xa6”。

我尝试了多种方法来解码这个

let s = "\\xc3\\xa6"
let dec = s.utf8

从这里我期待

print(dec)
> æ

等等。但它不起作用,它只会导致

print(dec)
> \xc3\xa6

如何在 Swift 5 中解码字符串中的 UTF-8 文字?

【问题讨论】:

  • 没有魔法。您只需要解析文本,转换为[UInt8],然后转换为Data,然后您可以将其放入String.init(bytes:encoding:) 初始化程序中。

标签: swift string utf-8 decode


【解决方案1】:

您只需解析字符串,将每个十六进制字符串转换为UInt8,然后使用String.init(byte:encoding:) 对其进行解码:

let s = "\\xc3\\xa6"
let bytes = s
    .components(separatedBy: "\\x")
    // components(separatedBy:) would produce an empty string as the first element
    // because the string starts with "\x". We drop this
    .dropFirst() 
    .compactMap { UInt8($0, radix: 16) }
if let decoded = String(bytes: bytes, encoding: .utf8) {
    print(decoded)
} else {
    print("The UTF8 sequence was invalid!")
}

【讨论】:

  • 感谢您的回答,这将返回正确的字符“æ”。但是如果字符串是这样的: >let s = "WiFiName\\xc3\\xa6Test" 那么它不会返回任何东西,因为字符串文字不是字符串的最后一部分?
  • 我接受了答案,因为它回答了我原来的问题。然而,我可能应该在现实生活环境中询问字符串,其中字符串文字只是常规字符串的一部分。因为我不确定如果字符是常规句子的一部分,这种方法会如何。因为这仅在字符与句子的其余部分分开时才有效。 IE。如果字符串是:let s = "\\xc3\\xa6Test"
  • @YoungChul 一种简单的方法是编写一个正则表达式来查找该特定部分。使用类似(\\x[\da-f]{2})+ 的东西。如果您对此有疑问,可以发布一个新问题。
猜你喜欢
  • 2022-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多