How do you decode utf8-literals like quot;xc3xa6quot; in Swift 5?(如何在SWIFT 5中解码像xc3xa6quot;这样的UTF8文字?)
本文介绍了如何在SWIFT 5中解码像&xc3xa6";这样的UTF8文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从蓝牙特征获取WiFi SSID的列表。每个SSID都表示为一个字符串,有些SSID具有这些UTF8字面值,如";xc3xa6";。
我尝试了多种方式进行解码
let s = "\xc3\xa6"
let dec = s.utf8
我希望如此
print(dec)
> æ
等,但它不起作用,它只会导致
print(dec)
> xc3xa6
如何在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!")
}
这篇关于如何在SWIFT 5中解码像&xc3xa6";这样的UTF8文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在SWIFT 5中解码像&xc3xa6";这样的UTF8文字?


猜你喜欢
- Android - 拆分 Drawable 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- android 4中的android RadioButton问题 2022-01-01