[IOS]字符串判断、移除emoji 表情

时间:2023-01-11 15:57:57


使用方法:

  NSString *testString=@"?西瓜?苹果?橘子";
NSString *testStringno=@"西瓜苹果橘子";
NSLog(@"%@",testString);
NSLog(@"%@",testStringno);
BOOL isIncludingEmoji = [testString isIncludingEmoji];
BOOL isIncludingEmoji2 = [testStringno isIncludingEmoji];
NSLog(@"%d",isIncludingEmoji);
NSLog(@"%d",isIncludingEmoji2);
NSString* removedEmoji = [testString removedEmojiString];
NSLog(@"%@",removedEmoji);

[IOS]字符串判断、移除emoji 表情


————————————————————添加方法——————————————

//头文件
#import <Foundation/Foundation.h>

@interface NSString (RemoveEmoji)

- (BOOL)isIncludingEmoji;

- (instancetype)removedEmojiString;

@end

m文件

#import "NSString+RemoveEmoji.h"

@implementation NSString (RemoveEmoji)

- (BOOL)isEmoji {
const unichar high = [self characterAtIndex: 0];

// Surrogate pair (U+1D000-1F77F)
if (0xd800 <= high && high <= 0xdbff) {
const unichar low = [self characterAtIndex: 1];
const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;

return (0x1d000 <= codepoint && codepoint <= 0x1f77f);

// Not surrogate pair (U+2100-27BF)
} else {
return (0x2100 <= high && high <= 0x27bf);
}
}

- (BOOL)isIncludingEmoji {
BOOL __block result = NO;

[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
if ([substring isEmoji]) {
*stop = YES;
result = YES;
}
}];

return result;
}

- (instancetype)removedEmojiString {
NSMutableString* __block buffer = [NSMutableString stringWithCapacity:[self length]];

[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
[buffer appendString:([substring isEmoji])? @"": substring];
}];

return buffer;
}

@end

楼主在github上爬到的。

附上地址:https://github.com/woxtu/NSString-RemoveEmoji  

网速差的同学就看看我的吧:)