unicode和中文的互相转化

项目中有评论的功能,当评论中有表情的时候不能正常显示,就需要将上传的text转成unicode,然后显示的时候在转成utf-8   直接上代码
中文转unicode:

- (NSString*)utf8ToUnicode:(NSString*)string

{

    NSUIntegerlength = [stringlength];

    NSMutableString *s = [NSMutableString stringWithCapacity:0];

    for(inti =0;i < length; i++)

    {

        unichar_char = [stringcharacterAtIndex:i];

        //判断是否为英文和数字

        if(_char <='9'&& _char >='0')

        {

            [sappendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];

        }

        elseif(_char >='a'&& _char <='z')

        {

            [sappendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];

        }

        elseif(_char >='A'&& _char <='Z')

        {

            [sappendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];

        }

        else

        {

            [sappendFormat:@"\\u%x",[stringcharacterAtIndex:i]];

        }

    }

    returns;

}


然后是unicode转中文:

- (NSString*) replaceUnicode:(NSString*)TransformUnicodeString

{


    NSString*tepStr1 = [TransformUnicodeString stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];


    NSString*tepStr2 = [tepStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];


    NSString*tepStr3 = [[@"\"" stringByAppendingString:tepStr2]stringByAppendingString:@"\""];


    NSData*tepData = [tepStr3 dataUsingEncoding:NSUTF8StringEncoding];


    NSString*axiba = [NSPropertyListSerialization  propertyListWithData:tepData options:NSPropertyListMutableContainers


                                                                   format:NULLerror:NULL];

    return [axiba    stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];


}

你可能感兴趣的:(unicode和中文的互相转化)