将unicode字符串截断为最大字节数

时间:2017-05-30 17:36:40

标签: swift string swift3 substring

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

例如:

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

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

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

1 个答案:

答案 0 :(得分:0)

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)'")
相关问题