Best way to convert Back and forth from Unichars t

2019-08-22 03:54发布

问题:

I am trying to understand Unichars. Coming from Ascii, Unichars just seems like a more advanced and complex library of character codes. Now I am building a simple application that will accept a string "\u####" that will represent the Unicode, that leads me to my first problem. what is the best way to format Unicode, after searching the web for so long, I feel like I have seen many ways to do it. Or maybe I just don't have the best concept of it yet.

Lets take the recycle symbol for example. U+267B

I would like my Program to convert that into the actual symbol, and display it?

Then id like to read in any symbol and convert that back into Unicode?

I am expecting this to be very simple, but I am trying to teach this to my self...

Thanks OverFlow!!!!

ps. Whats the command on a MacBook Pro to type in Unicode and have the corresponding symbol appear?

回答1:

This should work for you:

NSString *text = inputView.text; // For example "\u267B"
NSLog(@"%@", text);
// Output: \u267B
NSData *d = [text dataUsingEncoding:NSASCIIStringEncoding];
NSString *converted = [[NSString alloc] initWithData:d encoding:NSNonLossyASCIIStringEncoding];
NSLog (@"%@", converted);
// Output: ♻
outputView.text = converted;

It uses the fact that NSNonLossyASCIIStringEncoding decodes \uNNNN to the corresponding Unicode character.

To convert in the other direction (from "♻" to "\u267B"), you just have to exchange NSASCIIStringEncoding and NSNonLossyASCIIStringEncoding in the above code.

UPDATE: As you correctly noticed, the "reverse direction" does not encode characters in the range <= U+00FF. The following code converts these characters as well:

NSString *text = inputView.text; // For example "♻A"
NSLog(@"%@", text);
// Output: ♻A
NSMutableString *converted = [NSMutableString string];
for (NSInteger i = 0; i < [text length]; i++) {
    unichar c = [text characterAtIndex:i];
    [converted appendFormat:@"\\u%04X", c];
}
NSLog (@"%@", converted);
// Output: \u267B\u0041
outputView.text = converted;