到 FileHandle 指针和 Swift 4 中字符编码的索引距离



我有这个函数来返回(并寻找(一个特定单词的FileHandle指针:

func getFilePointerIndex(atWord word: String, inFile file: FileHandle) -> UInt64? {
    let offset = file.offsetInFile
    if let str = String(data: file.readDataToEndOfFile(), encoding: .utf8) {
        if let range = str.range(of: word) {
            let intIndex = str.distance(from: str.startIndex, to: range.lowerBound)
            file.seek(toFileOffset: offset + UInt64(intIndex))
            return UInt64(intIndex) + offset
        }
    }
    return nil
}

当应用于某些 utf8 文本文件时,它会产生远离传入单词位置的偏移结果。我认为它必须是字符编码(可变字节字符(,因为 seek(toFileOffset:(方法适用于类数据对象。

有什么想法可以修复它吗?

let intIndex = str.distance(from: str.startIndex, to: range.lowerBound)

Character s 为单位测量距离,即"扩展的 Unicode 字形集群"。例如,字符"€"将存储为三个字节"0xE2 0x82 0xAC"(UTF-8 编码(,但计为单个字节 Character .

要以 UTF-8 代码单位测量距离,请使用

let intIndex = str.utf8.distance(from: str.utf8.startIndex, to: range.lowerBound)

另请参阅 Swift 博客中的 Swift 2 中的字符串,了解有关字形簇和Swift 字符串的不同视图。

最新更新