Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing unicode char format for NSString

I have a list of unicode char "codes" that I'd like to print using \u escape sequence (e.g. \ue415), as soon as I try to compose it with something like this:

// charCode comes as NSString object from PList
NSString *str = [NSString stringWithFormat:@"\u%@", charCode];

the compiler warns me about incomplete character code. Can anyone help me with this trivial task?

like image 881
Eimantas Avatar asked Jan 06 '11 13:01

Eimantas


1 Answers

I think you can't do that the way you're trying - \uxxx escape sequence is used to indicate that a constant is a unicode character - and that conversion is processed at compile-time.

What you need is to convert your charCode to an integer number and use that value as format parameter:

unichar codeValue = (unichar) strtol([charCode UTF8String], NULL, 16);
NSString *str = [NSString stringWithFormat:@"%C", charCode];
NSLog(@"Character with code \\u%@ is %C", charCode, codeValue);

Sorry, that nust not be the best way to get int value from HEX representation, but that's the 1st that came to mind

Edit: It appears that NSScanner class can scan NSString for number in hex representation:

unichar codeValue;
[[NSScanner scannerWithString:charCode] scanHexInt:&codeValue];
...
like image 106
Vladimir Avatar answered Oct 08 '22 14:10

Vladimir