以下代码:
func printLengthOf(_ str: String) {
print("String: \(str)")
print("UTF8: \(str.lengthOfBytes(using: .utf8))")
print("UTF16: \(str.lengthOfBytes(using: .utf16))")
}
let emoji1 = ""
let emoji2 = ""
printLengthOf(emoji1)
printLengthOf(emoji2)
显示:
String:
UTF8: 4
UTF16: 4
String:
UTF8: 8
UTF16: 8
但是,Android将相同的表情符号算作2个字节,我认为同一表情符号的字节数不应该与平台有关。我做错了什么吗?
谢谢!
更新:
Android使用以下代码计算长度:
*byteLength = myString.getBytes("UTF-8").length;*