Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

ios - Converting escaped UTF8 characters back to their original form

I'm trying to read strings from an array that's coming from a plist and print those strings.

The strings in the array contain escaped UTF8 characters - for example "Nu?a Florjan?i?" becomes "Nuu0161a Florjanu010diu010d" when read from the plist. There is no way to change the content of the plist, but my program needs to display the names properly.

The strange thing is that Objective-C seems to do this automatically when I'm hardcoding the string. However, if I get the string from the plist nothing happens at all.

To give you an example, here's some code:

NSString *name1 = @"Nuu0161a Florjanu010diu010d";
NSString *name2 = [list objectAtIndex:0];       
NSLog(@"name 1: %@", name1);
NSLog(@"name 2: %@", name2);

[list objectAtIndex:0] contains @"Nuu0161a Florjanu010diu010d" - the only difference is that it has been set via the plist editor.

The console output is:

2011-10-22 18:00:02.595 Test[13410:11c03] name 1: Nu?a Florjan?i?
2011-10-22 18:00:02.595 Test[13410:11c03] name 2: Nuu0161a Florjanu010diu010d

I've tried all sorts of things, including transforming the string into a C-string and then creating an NSString object with a UTF-8 encoding but nothing worked at all.

I'd really appreciate any pointers from you that might help me solve this seemingly mundane problem.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like the string in the plist contains the characters "u0161" rather than the Unicode character number 0x161. So you need to decode the u escapes in the string you've extracted from the plist. NSString can do that for you using NSNonLossyASCIIStringEncoding:

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
    @autoreleasepool {
        NSString *name2escaped = @"Nu\u0161a Florjan\u010di\u010d";
        NSString *name2 = [NSString
            stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding]
            encoding:NSNonLossyASCIIStringEncoding];
        NSLog(@"name2 = %@", name2);
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...