Best way to convert Back and forth from Unichars to display characters? Objective C

吃可爱长大的小学妹 提交于 2019-12-25 05:24:19

问题


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;


来源:https://stackoverflow.com/questions/17759574/best-way-to-convert-back-and-forth-from-unichars-to-display-characters-objectiv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!