美文网首页
将表情描述转换成表情

将表情描述转换成表情

作者: child_cool | 来源:发表于2018-02-28 11:51 被阅读18次

@"{d83d}{de02}" 转换成 😂

- (int)hex2dec:(NSString *)hex {
    int dec=0;
    int len = [hex length];
    int i;
    for(i=len-1;i>=0;i--) {
        unichar c = [hex characterAtIndex:i];
        if(c >= '0' && c <='9'){
            dec += (c-48)<<(4*(len-i-1));
        }else if(c >= 'A' && c <='F'){
            dec += (c-55)<<(4*(len-i-1));
        }else if(c >= 'a' && c <='f'){
            dec += (c-87)<<(4*(len-i-1));
        }
    }
    return dec;
}

/**
 * 将表情描述转换成表情
 *
 * @param str
 * @return
 */
- (NSString*)getEmoji:(NSString*)str {
    
    NSString *string = str;
    NSString *strRegex = @"\\{(.*?)\\}";
    
    NSError *error = nil;
    //创建正则表达式对象
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:strRegex options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&error];
    //无视大小写.
    NSArray *matches = [reg matchesInString:string options:NSMatchingCompleted range:NSMakeRange(0, [string length])];
    
    NSString *originString = [string copy];
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        NSString *s1 = [originString substringWithRange:NSMakeRange(range.location, range.length)];
        NSString *s2 = [s1 substringWithRange:NSMakeRange(1, s1.length - 2)];
        NSString *s3;
        
        @try{
            s3 = [NSString stringWithFormat:@"%C", (unichar)[self hex2dec:s2]];
            
            NSLog(@"s1: %@", s1);
            NSLog(@"s2: %@", s2);
            NSLog(@"s3: %@", s3);
            
            string = [string stringByReplacingOccurrencesOfString:s1 withString:s3];
        } @catch(NSException *e) {
            NSLog(@"%@", e);
        }
    }
    
    return string;
}

相关文章

网友评论

      本文标题:将表情描述转换成表情

      本文链接:https://www.haomeiwen.com/subject/mzebxftx.html