猿问

Swift 中判断字符串是否有 Emoji 表情

Swift 中判断字符串是否有 Emoji 表情


芜湖不芜
浏览 1377回答 2
2回答

米琪卡哇伊

使用遍历用 OC 实现的扩展:@implementation NSString (Emoji)+ (BOOL)stringContainsEmoji:(NSString *)string{__block BOOL returnValue = NO;[string enumerateSubstringsInRange:NSMakeRange(0, [string length])options:NSStringEnumerationByComposedCharacterSequencesusingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {const unichar hs = [substring characterAtIndex:0];if (0xd800 <= hs && hs <= 0xdbff) {if (substring.length > 1) {const unichar ls = [substring characterAtIndex:1];const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;if (0x1d000 <= uc && uc <= 0x1f77f) {returnValue = YES;}}} else if (substring.length > 1) {const unichar ls = [substring characterAtIndex:1];if (ls == 0x20e3) {returnValue = YES;}} else {if (0x2100 <= hs && hs <= 0x27ff) {returnValue = YES;} else if (0x2B05 <= hs && hs <= 0x2b07) {returnValue = YES;} else if (0x2934 <= hs && hs <= 0x2935) {returnValue = YES;} else if (0x3297 <= hs && hs <= 0x3299) {returnValue = YES;} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {returnValue = YES;}}}];return returnValue;}其实它的原理还是去匹配 Emoji 所在区间,所以,如果我们应用上 Swift 语句以及其特性,那么 Swift 版本就是这样:extension String {var containsEmoji: Bool {for scalar in unicodeScalars {switch scalar.value {case0x00A0...0x00AF,0x2030...0x204F,0x2120...0x213F,0x2190...0x21AF,0x2310...0x329F,0x1F000...0x1F9CF:return truedefault:continue}}return false}}

慕标5832272

-(BOOL)stringContainsEmoji:(NSString *)string {__block&nbsp;BOOL&nbsp;returnValue =&nbsp;NO;[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange,&nbsp;BOOL&nbsp;*stop) {const unichar hs = [substring characterAtIndex:0];// surrogate pairif (0xd800 <= hs && hs <= 0xdbff) {if (substring.length > 1) {const unichar ls = [substring characterAtIndex:1];const int&nbsp;uc&nbsp;= ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;if (0x1d000 <=&nbsp;uc&nbsp;&&&nbsp;uc&nbsp;<= 0x1f77f) {returnValue = YES;}}} else if (substring.length > 1) {const unichar ls = [substring characterAtIndex:1];if (ls == 0x20e3) {returnValue = YES;}} else {//&nbsp;non surrogateif (0x2100 <= hs && hs <= 0x27ff) {returnValue = YES;} else if (0x2B05 <= hs && hs <= 0x2b07) {returnValue = YES;} else if (0x2934 <= hs && hs <= 0x2935) {returnValue = YES;} else if (0x3297 <= hs && hs <= 0x3299) {returnValue = YES;} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {returnValue = YES;}}}];return returnValue;}
随时随地看视频慕课网APP
我要回答