我正在从蓝牙特性中获取 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
,然后用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!")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)