如何从包含表情符号的Swift字符串中正确获取子字符串?

时间:2018-11-15 10:05:08

标签: ios swift xcode twitter unicode

我不明白这是怎么回事:

let strA = "0123456789"
let fromA = String.Index(encodedOffset: 2)
let toA = String.Index(encodedOffset: 8)
print("\(String(strA[fromA..<toA]))") // Prints "234567".

let strB = "01235689"
let fromB = String.Index(encodedOffset: 2)
let toB = String.Index(encodedOffset: 8)
print("\(String(strB[fromB..<toB]))") // Prints "23".

我希望最底行打印"2356",但它打印"23"。这似乎与unicode代码点和部分砍掉unicode表情符号最后一个字符有关。

如何使用可见字符的偏移量获得期望的"2356"字符串?

我的问题源于Twitter的API及其扩展的tweets JSON对象,这些对象要求您使用display_text_range值将tweet文本切成大小。现在,只要鸣叫中有表情符号,我的代码就会崩溃,因为如上所述,我的子字符串代码会破坏字符串。

1 个答案:

答案 0 :(得分:0)

以下内容可以满足我的要求,并打印"2356"

let strB = "01235689"
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)
相关问题