我有一个字符串“hi @😀”。如果我检查这个字符串的长度,它会是 6。如果我写 string.characters[5] ,就会出现数组索引越界异常。为什么?如何提取😀.?
检查我使用 string.utf16.count 的长度。
您会收到错误,因为表情符号表示为 Unicode 字符,其长度不一定为 1,因此您应该始终使用从 .index(of:) 函数获取的索引来访问字符串中的字符包含表情符号。
看看这个游乐场片段,它向您展示了如何安全地从字符串中获取表情符号。
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]
}
U获取utf16字符串的长度
所以如果你想这样做:string.characters[5]
喜欢 string.utf16.characters[5]