swift - swift 中带有表情符号的子字符串

标签 swift string swift3

我有一个字符串“hi @😀”。如果我检查这个字符串的长度,它是 6。如果我写 string.characters[5] 获取数组索引超出绑定(bind)异常。为什么 ??如何提取😀.?

检查长度,我正在使用 string.utf16.count。

最佳答案

你得到这个错误是因为表情符号被表示为 Unicode 字符,它的长度不一定为 1,所以你应该总是使用从 .index(of:) 函数获得的索引来访问字符包含表情符号的字符串。

看看这个 Playground 片段,它向您展示了如何安全地从字符串中获取表情符号。

let s = "hi @😀 , bye ☀️ asd"
s.characters.count
s.characters.index(of: "😀")
if let emojiIndex = s.characters.index(of: "😀") {
    s[emojiIndex]
}
s.characters.index(of: "☀️")
if let emojiIndex = s.characters.index(of: "☀️") {
    s[emojiIndex]
}

关于swift - swift 中带有表情符号的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436566/

相关文章:

regex - R 中按条件分割字符串

ios - 在 Controller 之间传递数据显示错误

ios - swift & PromiseKit : Resolving ALL promises from a loop

ios - TableView 未填充数据

xcode - 两个目标和两个 Localized.Strings(一个基础)

c# - 从字符串中获取 HTML 标签

c# - 在 C# 中检查字符串是否有大写字母的最快方法是什么?

ios - 将解析后的数据保存到数组中

swift - 在从NotificationCenter接收通知时如何用publisher替换addObserver

swift - 无法初始化应用程序保存的数据