【问题标题】:How can I correctly get a substring from Swift string that contains with emojis?如何从包含表情符号的 Swift 字符串中正确获取子字符串?
【发布时间】:2019-04-18 09:43:33
【问题描述】:

我不明白这里发生了什么:

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 及其扩展推文 JSON 对象,这些对象要求您使用 display_text_range 值将推文文本缩小到合适的大小。现在,只要推文中有表情符号,我的代码就会崩溃,因为如上所述,我的子字符串代码会破坏字符串。

【问题讨论】:

  • 为什么这么复杂? let truncatedString = String(str.prefix(maximalLength)) 呢?
  • @MartinR 他将无法使用前缀方法获取子字符串。
  • @Dan:看看How does String substring work in Swift,它解释了问题并显示了解决问题的各种方法。
  • @MartinR 谢谢!这个答案确实有帮助。我现在将回答我自己的问题。

标签: ios swift xcode twitter unicode


【解决方案1】:

下面做我想要的并打印"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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2020-03-24
    • 2018-05-13
    • 2016-05-26
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多