iOS-带emoji表情的字符串长度限制

/**
 裁剪带表情的字符串
 
 @param string 字符串
 @param limit 字数限制
 @return 裁剪后的字符串
 */
+ (NSString *)clipEmojiString:(NSString *)string ByLimit:(NSUInteger)limit {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *array = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
    if (array.count) {
        NSRange range;
        NSInteger count = 0;
        for (NSUInteger index = 0; index < string.length; index += range.length) {
            range = [string rangeOfComposedCharacterSequenceAtIndex:index];
            if (++count == limit + 1) {
                string = [string substringToIndex:range.location];
                break;
            }
        }
    }else{
        if (string.length > limit) {
            string = [string substringToIndex:limit];
        }
    }
    return string;
}

推荐阅读更多精彩内容