美文网首页
unicode与utf8编码相互转化

unicode与utf8编码相互转化

作者: 欠揍的葡萄 | 来源:发表于2017-03-29 16:06 被阅读0次
    - (NSString *) packUtf8ToUnicode:(NSString *)string
    {
        NSUInteger length = [string length];
        NSMutableString *s = [NSMutableString stringWithCapacity:0];
        for (int i = 0;i < length; i++) {
            unichar _char = [string characterAtIndex:i];
            if (_char <= '9' && _char >= '0') {
                [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            }else if(_char >= 'a' && _char <= 'z')
            {
                [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            }else if(_char >= 'A' && _char <= 'Z')
            {
                [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            }else
            {
                [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
            }
    
        }
        return s;
    }
    
    - (NSString *)unPackUnicode:(NSString *)unicodeStr {
        NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
        NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
        NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
        NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                               mutabilityOption:NSPropertyListImmutable
                                                                         format:NULL
                                                               errorDescription:NULL];
        
        return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
    }
    
    

    相关文章

      网友评论

          本文标题:unicode与utf8编码相互转化

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