String.utf16.index(_:offsetBy :)在包含表情符号的字符串上无法正常工作

我正在编写代码,将string2中出现的所有string1替换为string3。例如:

string1: "he"
string2: "hello everybody. I'm here to help you."
string3: "XY"
output:  "XYllo everybody. I'm XYre to XYlp you."

一路走来,我注意到如果string1或string2包含表情符号,我的方法将无法正常工作。我写了一小段代表问题的代码:

let strA = "Hello,My fried"
let strB = "Hi,My fried"
let strC = "??‍♂️,My fried"


let offsetBA = "Hi".utf16.count - "Hello".utf16.count
let offsetCA = "??‍♂️".utf16.count - "Hello".utf16.count

let idx1 = strA.utf16.index(strA.utf16.startIndex,offsetBy: 11)
print(strA[idx1]) // Output: i

let idx2 = strB.utf16.index(idx1,offsetBy: offsetBA)
print(strB[idx2]) // Output: i

let idx3 = strC.utf16.index(idx1,offsetBy: offsetCA)
print(strC[idx3]) // Output:,

总而言之,有3个字符串,我创建了一个索引(idx1),该索引指向第一个字符串中的i。我知道第二个字符串以Hello开头,而不是Hi,第三个字符串以表情符号开头。因此,我想调整idx1并将结果存储在idx2idx3中,使它们仍分别指向string2和string3中的i。该计算适用于全ASCII字符串2,但不适用于字符串3(idx指向,)。 我研究了StringUTF16ViewString.Index的实现,但是可以找到原因。我在Swift5.1和Swift4上运行了这段代码。

haihaome1 回答:String.utf16.index(_:offsetBy :)在包含表情符号的字符串上无法正常工作

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3100512.html

大家都在问