为NSString编写unicode char格式

时间:2011-01-06 13:42:55

标签: objective-c nsstring

我有一个unicode char“代码”列表,我想用\u转义序列(例如\ue415)打印,只要我尝试用这样的东西组成它:

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

编译器警告我不完整的字符代码。任何人都可以帮我完成这项微不足道的工作吗?

3 个答案:

答案 0 :(得分:14)

我认为你不能按照你尝试的方式做到这一点 - \ uxxx转义序列用于表示一个常量是一个unicode字符 - 并且该转换是在编译时处理的。

您需要将charCode转换为整数并将该值用作格式参数:

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

很抱歉,这不是从HEX表示中获取int值的最佳方式,但这是第一个想到的

修改NSScanner类似乎可以扫描NSString以十六进制表示的数字:

unichar codeValue;
[[NSScanner scannerWithString:charCode] scanHexInt:&codeValue];
...

答案 1 :(得分:1)

请注意,并非所有字符都可以用UTF-8编码。我昨天遇到了一个错误,其中一些韩文字符无法正确编码为UTF-8。

我的解决方法是将格式字符串从%s更改为%@并避免重新编码问题,尽管这可能不适合您。

答案 2 :(得分:0)

根据@Vladimir的代码,这对我有用:

NSUInteger codeValue;
[[NSScanner scannerWithString:@"0xf8ff"] scanHexInt:&codeValue];
NSLog(@"%C", (unichar)codeValue);

不是来自API文档“

The hexadecimal integer representation may optionally be preceded
by 0x or 0X. Skips past excess digits in the case of overflow,
so the receiver’s position is past the entire hexadecimal representation.