swift 根据UTF8获取包含表情符号的字符串的NSR范围

yc0p9oo0  于 2023-02-28  发布在  Swift
关注(0)|答案(1)|浏览(159)

我怎样才能得到字符串的NSRange包含表情符号根据UTF8?我的代码:

let str = "🎁🇵🇷"
for char in str {
    if let range = str.range(of: "\(char)") {
        let nsRange = NSRange(range, in: str)
        print("utf8 Count:", String(char).utf8.count, "utf16 Count:", String(char).utf16.count, "nsRange", nsRange)
    }
}

结果:

utf8 Count: 4 utf16 Count: 2 nsRange {0, 2}
utf8 Count: 8 utf16 Count: 4 nsRange {2, 4}
    • 预期:nsRange {0,4},然后nsRange {4,8}**
mefy6pfw

mefy6pfw1#

我不知道为什么UTF-8 NSRange是有用的,但不管怎样,你可以这样做:

let str = ... // given a String
let range = ... // and a Range<String.Index> in that string...

let substring = str[range] // get the substring of that range in that string
// get everything before substring, so we can calculate the UTF-8 offset 
// of the lower bound of the range by counting the UTF-8 bytes in everythingBefore
let everythingBefore = str[..<range.lowerBound]

// create the NSRange with the lower bound and length of the substring
print(NSRange(location: everythingBefore.utf8.count, length: substring.utf8.count))

对示例字符串中的所有字符执行此操作:

let str = "🎁🇵🇷"
for index in str.indices {
    let range = index...index
    let substring = str[range]
    let everythingBefore = str[..<range.lowerBound]
    print(NSRange(location: everythingBefore.utf8.count, length: substring.utf8.count))
}

以上代码输出:

{0, 4}
{4, 8}

相关问题