【问题标题】:Truncate unicode string to max bytes将 unicode 字符串截断为最大字节
【发布时间】:2017-05-30 17:36:39
【问题描述】:

我需要将一个(可能很大的)unicode 字符串截断为最大大小(以字节为单位)。转换为 UTF-16 然后再转换回来似乎不可靠。

例如:

let flags = "????????????????"
let result = String(flags.utf16.prefix(3))

在这种情况下,结果为零。

我需要一种有效的方法来执行此截断。想法?

【问题讨论】:

  • 你需要 8 而不是 3

标签: swift string swift3 substring


【解决方案1】:

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)'")

【讨论】:

  • 这真的很接近,但是我注意到一个问题: print(String("welcome to ?? and ??".firstBytes(10))!.lengthOfBytes(using: .unicode))输出:20
  • Unicode 标量是 21 位的,但 Swift 可能会在幕后做一些魔术来将其存储为 UTF-16(这是 NSString 内部使用的)。如果您想要可以表示字符串的最少字节数,请使用 UTF-8
  • 是的,每个 unicode 标量至少为 2 个字节,而拉丁字符在 utf8 中为 1 个字节。因此,这会将 utf8 字符串截断为一组字节数。但是,在这种情况下,存储编码不取决于我,我需要将 unicode 字符串截断为最大字节数。
  • 如果你的存储是一个数据库,我怀疑已经有一种机制来处理字符串截断。 Unicode 不是一种编码,它是 Swift 的术语。接收端使用什么,UTF-16 还是 UTF-8?
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2017-04-16
  • 2011-08-05
相关资源
最近更新 更多