PDA

View Full Version : Question about NSString encoding




Clouds
Jan 22, 2011, 03:00 PM
Hi,
I have a question about encoding a NSString
I want to convert this string:
寫在2011的開端

to this encoded string:
\U5beb\U57282011\U7684\U958b\U7aef
(don't know what encoding code is this)

but I don't know how to do.

I also tested with this method:

NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)string, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);

but it returns a string like this:

%E5%AF%AB%E5%9C%A82011%E7%9A%84%E9%96%8B%E7%AB%AF

which doesn't satisfy my need.
There's another issue with this method that it doen't keep the format of the text, it remove all 'newline \n' character so the encoded string returned in one line only. How can I solve that?

Thanks!



Clouds
Jan 23, 2011, 08:26 AM
Nevermind, I can do it by myself:

NSString *string = @"寫在2011的開端";
NSData *data = [string dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *encodedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", encodedString);
[encodedString release];