开发者

converting strings containing \u#### to characters on iOS iPhone

I receive a JSON response in a NSData Variable, and then convert the NSDATA into NSString:

NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

The problem is this string now contains character sequences of teh format \u##开发者_如何学JAVA##. (for example, Joe\u2019s).

I want to convert all such occurrences with their single character representation. (for example Joe\u2019s should become Joe's.

Any ideas on how to do this?

Also, could someone point me to a resource where i can learn the right terminology for this?

Thanks a lot!


I looked for a answer to this question for far too long today... finally just bit the bullet and wrote my own category on NSString. Feel free to correct mistakes, I'm not a unicode wizard. This definitely doesn't handle unicode past \uffff but I don't need that in my situation.

@interface NSString (UnicodeAdditions)
-(NSString *) unescapeUnicode;
@end

@implementation NSString (UnicodeAdditions)

-(NSString *) unescapeUnicode {
    NSString *input = self;
    int x = 0;
    NSMutableString *mStr = [NSMutableString string];

    do {
        unichar c = [input characterAtIndex:x];
        if( c == '\\' ) {
            unichar c_next = [input characterAtIndex:x+1];
            if( c_next == 'u' ) {

                unichar accum = 0x0;
                int z;
                for( z=0; z<4; z++ ) {
                    unichar thisChar = [input characterAtIndex:x+(2+z)];
                    int val = 0;
                    if( thisChar >= 0x30 && thisChar <= 0x39 ) { // 0-9
                        val = thisChar - 0x30;
                    }
                    else if( thisChar >= 0x41 && thisChar <= 0x46 ) { // A-F
                        val = thisChar - 0x41 + 10;
                    }
                    else if( thisChar >= 0x61 && thisChar <= 0x66 ) { // a-f
                        val = thisChar - 0x61 + 10;
                    }
                    if( z ) {
                        accum <<= 4;
                    }

                    accum |= val;
                }
                NSString *unicode = [NSString stringWithCharacters:&accum length:1];
                [mStr appendString:unicode];

                x+=6;
            }
            else {
                [mStr appendFormat:@"%c", c];
                x++;
            }           
        }
        else {
            [mStr appendFormat:@"%c", c];
            x++;
        }
    } while( x < [input length] );

    return( mStr );
}

@end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜