Swift: Sting没有length方法,获取字符串长度使用count;
OC: NSString使用.length获取长度;
场景:在存在emoji的的字符串下,Swift和OC混编时候如果用count取,导致匹配长度不够;
- NSString是由UTF-16单元构成
- length方法返回的是基于UTF-16的长度
- Swift的count返回的只是Unicode字符个数
结论: Swift的utf16.count是对应NSString的.length方法
private func allRangeOf(searchString: String, from: String) -> [NSRange] {
let scanner = Scanner(string: from)
scanner.caseSensitive = true
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "")
scanner.scanLocation = 0
var rangeArray: [NSRange] = []
while !scanner.isAtEnd {
if scanner.scanString(searchString, into: nil) {
let location = scanner.scanLocation - searchString.length
let range = NSRange(location: location, length: searchString.length)
rangeArray.append(range)
} else {
scanner.scanLocation += 1
}
}
return rangeArray
}
|