为 NSString 编写 unicode 字符格式 [英] Composing unicode char format for NSString

查看:50
本文介绍了为 NSString 编写 unicode 字符格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

我认为您不能按照您尝试的方式这样做 - \uxxx 转义序列用于指示常量是一个 Unicode 字符 - 而且转换在编译时处理.

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.

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

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);

抱歉,这肯定不是从十六进制表示中获取 int 值的最佳方法,但这是第一个想到的方法

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

看来 NSScanner 类可以扫描 NSString 以获取十六进制表示的数字:

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

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

这篇关于为 NSString 编写 unicode 字符格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆