将字符串中给定的 UTF8 NSRange 转换为 UTF16 NSRange

问题描述 投票:0回答:1

将字符串中任何给定的 UTF8 NSRange 转换为 UTF16 NSRange

例子:

let str = #"let 🎁🇵🇷 = "hello world""#

//The UTF8 NSRange of 🎁🇵🇷 is: {4, 12}
//The UTF16 NSRange of 🎁🇵🇷 is: {4, 6}

//The UTF8 NSRange of let 🎁🇵🇷 is: {0, 16}
//The UTF16 NSRange of let 🎁🇵🇷 is: {0, 10}

测试次数:

print("🎁🇵🇷".utf8.count) //12
print("🎁🇵🇷".utf16.count) //6

print("let 🎁🇵🇷".utf8.count) //16
print("let 🎁🇵🇷".utf16.count) //10

我只有 UTF8 范围,所以我需要将它们中的任何一个转换为 UTF16 范围。

提前谢谢你。

swift range nsrange
1个回答
1
投票

类似于在

查找字符串的第n个字符时使用
index(_:offsetBy:)获取第n个索引,您可以在此处使用相同的方法,除了字符串的
UTF8View

找到范围的开始和结束索引为

String.Index
,然后创建一个
Range<String.Index>
。然后你可以从中创建一个
NSRange

let str = #"let 🎁🇵🇷 = "hello world""#
let utf8Range = NSRange(location: 4, length: 12)
let startIndex = str.utf8.index(str.utf8.startIndex, offsetBy: utf8Range.lowerBound)
let endIndex = str.utf8.index(startIndex, offsetBy: utf8Range.length)
let stringRange = startIndex..<endIndex
let utf16Range = NSRange(stringRange, in: str)
print(utf16Range)
© www.soinside.com 2019 - 2024. All rights reserved.