我有一个方法可以检测字符串中的 url,并返回 url 和可以找到它们的范围。一切正常,直到字符串上出现表情符号。例如:
"I'm gonna do this callenge as soon as I can swing again 😂😂😂\n http://youtu.be/SW_d3fGz1hk"
由于表情符号,从文本中提取的 url 是 http://youtu.be/SW_d3fGz1而不是 http://youtu.be/SW_d3fGz1hk .我认为最简单的解决方案是将字符串中的表情符号替换为空白字符(因为我需要正确的范围来处理某些文本样式)。问题是,使用 Swift 很难做到这一点(很可能我缺乏使用 Swift String API 的能力)。
我一直在尝试这样做,但似乎我无法从一个 unicode 点数组创建一个字符串:
var emojilessStringWithSubstitution: String {
let emojiRanges = [0x1F601...0x1F64F, 0x2702...0x27B0]
let emojiSet = Set(emojiRanges.flatten())
let codePoints: [UnicodeScalar] = self.unicodeScalars.map {
if emojiSet.contains(Int($0.value)) {
return UnicodeScalar(32)
}
return $0
}
return String(codePoints)
}
我是不是以错误的方式解决了这个问题?在这里替换表情符号是最好的解决方案吗?如果可以,我该怎么做?
最佳答案
swift 5
不要使用这种硬编码
方式来检测emojis
。在 Swift 5
中,您可以轻松做到这一点
let inputText = "Some 🖐string 😂😂😂 with 👹👹 👹 emoji 🖐"
let textWithoutEmoij = inputText.unicodeScalars
.filter { !$0.properties.isEmojiPresentation }
.reduce("") { $0 + String($1) }
print(textWithoutEmoij) // Some string with emoji
关于string - Swift - 用空格替换字符串中的表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36919125/