How to convert unicode hex number variable to character in NSString?

混江龙づ霸主 提交于 2020-01-03 03:52:04

问题


Now I have a range of unicode numbers, I want to show them in UILabel, I can show them if i hardcode them, but that's too slow, so I want to substitute them with a variable, and then change the variable and get the relevant character. For example, now I know the unicode is U+095F, I want to show the range of U+095F to U+096f in UILabel, I can do that with hardcode like

NSString *str = [NSString stringWithFormat:@"\u095f"];

but I want to do that like

NSInteger hex = 0x095f;

[NSString stringWithFormat:@"\u%ld", (long)hex];

I can change the hex automatically,just like using @"%ld", (long)hex, so anybody know how to implement that?


回答1:


You can initialize the string with the a buffer of bytes of the hex (you simply provide its pointer). The point is, and the important thing to notice is that you provide the character encoding to be applied. Specifically you should notice the byte order.

Here's an example:

UInt32 hex = 0x095f;
NSString *unicodeString = [[NSString alloc] initWithBytes:&hex length:sizeof(hex) encoding:NSUTF32LittleEndianStringEncoding];

Note that solutions like using the %C format are fine as long as you use them for 16-bit unicode characters; 32-bit unicode characters like emojis (for example: 0x1f601, 0x1f41a) will not work using simple formatting.




回答2:


You would have to use

[NSString stringWithFormat:@"%C", (unichar)hex];

or directly declare the unichar (unsigned short) as

unichar uni = 0x095f;
[NSString stringWithFormat:@"%C", uni];

A useful resource might be the String Format Specifiers, which lists %C as

16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit.




回答3:


Like this:

unichar charCode = 0x095f;
NSString *s = [NSString stringWithFormat:@"%C",charCode];
NSLog(@"String = %@",s); //Output:String = य़


来源:https://stackoverflow.com/questions/30816793/how-to-convert-unicode-hex-number-variable-to-character-in-nsstring

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