Converting scanLocation from utf16 units to charac

2019-07-18 05:31发布

In Swift 3.0 (NS)Scanner, string property returns the string being parsed and scanLocation returns the current scan location. I'm trying to extract the parsed text:

var parsedText: String {
    return string.substring(to: string.index(string.startIndex, offsetBy: scanLocation))
}

This code crashes when string contains multibyte characters. It turned out that scanLocation returns number of utf16 units, not number of characters parsed.

How to convert scanLocation (code units) into character index?

Playground for experimenting:

let scanner = Scanner(string: "Hello                

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-18 06:06

To obtain character index:

import Foundation

extension Scanner {
    var scanLocationInCharacters: Int {
        let utf16 = string.utf16
        guard let to16 = utf16.index(utf16.startIndex, offsetBy: scanLocation, limitedBy: utf16.endIndex),
            let to = String.Index(to16, within: string) else {
                return 0
        }
        return string.distance(from: string.startIndex, to: to)
    }
}

let scanner = Scanner(string: "Hello                                                                    
查看更多
登录 后发表回答