我需要将一个(可能很大)unicode 字符串截断为最大大小(以字节为单位)。转换为 UTF-16 然后再转换回来似乎不可靠。
例如:
let flags = "🇵🇷🇵🇷"
let result = String(flags.utf16.prefix(3))
在这种情况下结果为零。
我需要一种有效的方法来执行此截断。有想法吗?
最佳答案
Swift 中的字符串采用 UnicodeScalar
,每个标量可以存储多个字节。如果您无论如何都只获取前 n
个字节,那么当您将它们转换回来时,这些字节很可能不会以任何编码形式形成正确的子字符串。
现在,如果您将定义更改为“占用可以形成有效子字符串的前 n
个字节”,则可以使用 UTF8View
:
extension String {
func firstBytes(_ count: Int) -> UTF8View {
guard count > 0 else { return self.utf8.prefix(0) }
var actualByteCount = count
while actualByteCount > 0 {
let subview = self.utf8.prefix(actualByteCount)
if let _ = String(subview) {
return subview
} else {
actualByteCount -= 1
}
}
return self.utf8.prefix(0)
}
}
let flags = "welcome to 🇵🇷 and 🇺🇸"
let bytes1 = flags.firstBytes(11)
// the Puerto Rico flag character take 8 bytes to store
// so the actual number of bytes returned is 11, same as bytes1
let bytes2 = flags.firstBytes(13)
// now you can cover the string up to the Puerto Rico flag
let bytes3 = flags.firstBytes(19)
print("'\(bytes1)'")
print("'\(bytes2)'")
print("'\(bytes3)'")
关于swift - 将 unicode 字符串截断为最大字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44268546/