swift - 将 unicode 字符串截断为最大字节

标签 swift string swift3 substring

我需要将一个(可能很大)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/

相关文章:

ios - 如何在 Swift 中调整图像大小?

string - 在 R 中生成子字符串和随机字符串

ios - 来自位于另一个数组中的数组的 ParseJson 数据

ios - 在 NSBatchDeleteRequest 之后使用核心数据

ios - 如何使用 Swift 4 在 UITextfield 中实现 Material chips

ios - Swift:无法使用 NSObjects 将类型 'NSNull' 的值转换为 'NSDictionary'

swift - 如何在真实应用中实现 CallKit?

string - 管理 CStringArray 条目

c - 在C中将2个ascii字符存储到1个整数中

ios - 如何在定时器选择器上传递参数