[英]How can I correctly get a substring from Swift string that contains with emojis?
我不明白這是怎么回事:
let strA = "0123456789"
let fromA = String.Index(encodedOffset: 2)
let toA = String.Index(encodedOffset: 8)
print("\(String(strA[fromA..<toA]))") // Prints "234567".
let strB = "0123🇻🇬56😍89"
let fromB = String.Index(encodedOffset: 2)
let toB = String.Index(encodedOffset: 8)
print("\(String(strB[fromB..<toB]))") // Prints "23🇻🇬".
我希望最底行打印"23🇻🇬56😍"
但它打印"23🇻🇬"
。 這似乎與Unicode代碼點和部分砍掉最后一個Unicode表情符號字符的部分有關。
如何使用可見字符的偏移量獲得期望的"23🇻🇬56😍"
字符串?
我的問題源於Twitter的API及其擴展的tweets JSON對象,這些對象要求您使用display_text_range
值將tweet文本切成大小。 現在,只要鳴叫中有表情符號,我的代碼就會崩潰,因為如上所述,我的子字符串代碼破壞了字符串。
以下是我想要的,並打印"23🇻🇬56😍"
。
let strB = "0123🇻🇬56😍89"
print("String count \(strB.count).")
let fromB = strB.index(strB.startIndex, offsetBy: 2)
let toB = strB.index(strB.startIndex, offsetBy: 8)
print("\(String(strB[fromB..<toB]))")
注意而不是使用:
let fromB = String.Index(encodedOffset: 2)
let toB = String.Index(encodedOffset: 8)
我用:
let fromB = strB.index(strB.startIndex, offsetBy: 2)
let toB = strB.index(strB.startIndex, offsetBy: 8)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.