随着最近添加的iOS 9.1表情符号,以及可用肤色等,你如何正确计算字符串中的表情符号的数量,假设字符串是由表情符号唯一组成的?
记住,表情符号的长度可能会有所不同。
NSString.length或string.characters.count
"“返回2
"✊“返回4
"“或"”或"“返回1!
"“返回4(通常显示为1个家庭表情)
等等。
发布于 2015-11-11 13:01:02
我做了一个String的扩展来统计字符串中的表情符号数量:
extension String {
func countEmojiCharacter() -> Int {
func isEmoji(s:NSString) -> Bool {
let high:Int = Int(s.characterAtIndex(0))
if 0xD800 <= high && high <= 0xDBFF {
let low:Int = Int(s.characterAtIndex(1))
let codepoint: Int = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000
return (0x1D000 <= codepoint && codepoint <= 0x1F9FF)
}
else {
return (0x2100 <= high && high <= 0x27BF)
}
}
let nsString = self as NSString
var length = 0
nsString.enumerateSubstringsInRange(NSMakeRange(0, nsString.length), options: NSStringEnumerationOptions.ByComposedCharacterSequences) { (subString, substringRange, enclosingRange, stop) -> Void in
if isEmoji(subString!) {
length++
}
}
return length
}
}测试:
let y = "xxxzzz"
print(y.countEmojiCharacter())
// result is 3发布于 2016-04-18 18:36:01
尝试此代码片段
extension String {
var composedCount : Int {
var count = 0
enumerateSubstringsInRange(startIndex..<endIndex, options: .ByComposedCharacterSequences) {_ in count++}
return count
}
}:功劳归于ericasadun
发布于 2016-01-26 01:36:37
您可以使用此代码example或此pod。
要在Swift中使用,请将类别导入YourProject_Bridging_Header
#import "NSString+EMOEmoji.h"然后你可以检查字符串中每个表情符号的范围:
let example: NSString = "stringwithemojis✊" //string with emojis
let emojiCount: NSInteger = example.emo_emojiCount() // count
print(emojiCount)
// Output: ["3"]I created an small example project with the code above.
更新
在>= iOS 8.3中运行此代码将具有
// Output: ["3"]使用< iOS 8.3运行此代码将会有一个
// Output: ["7"]这是因为iOS 8.3引入了家庭表情符号、肤色和其他许多表情符号。因此,一个较小的iOS版本正在以不同的方式解读这个表情符号。
例如,在Safari,Firefox和Chrome中打开这篇文章,看看有什么不同。
https://stackoverflow.com/questions/33641962
复制相似问题