如何在 Objective-C 中将 unichar 值转换为 NSString? [英] How to convert a unichar value to an NSString in Objective-C?

查看:48
本文介绍了如何在 Objective-C 中将 unichar 值转换为 NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 unichar 变量中存储了一个国际字符.此字符不是来自文件或 url.该变量本身只存储一个 UTF-8 格式的无符号短(0xce91)并转换为希腊大写字母A".我试图将该字符放入一个 NSString 变量中,但我失败了.

I've got an international character stored in a unichar variable. This character does not come from a file or url. The variable itself only stores an unsigned short(0xce91) which is in UTF-8 format and translates to the greek capital letter 'A'. I'm trying to put that character into an NSString variable but i fail miserably.

我尝试了两种不同的方法,但都没有成功:

I've tried 2 different ways both of which unsuccessful:

unichar greekAlpha = 0xce91; //could have written greekAlpha = 'Α' instead.

NSString *theString = [NSString stringWithFormat:@"Greek Alpha: %C", greekAlpha];

不好.我得到了一些奇怪的汉字.作为旁注,这与英文字符完美搭配.

No good. I get some weird chinese characters. As a sidenote this works perfectly with english characters.

然后我也试过这个:

NSString *byteString = [[NSString alloc] initWithBytes:&greekAlpha
                                                length:sizeof(unichar)
                                              encoding:NSUTF8StringEncoding];

但这也行不通.我显然做错了什么,但我不知道是什么.有人能帮助我吗 ?谢谢!

But this doesn't work either. I'm obviously doing something terribly wrong, but I don't know what. Can someone help me please ? Thanks!

推荐答案

因为 0xce91 是 UTF-8 格式,而 %C 希望它是 UTF-16 像上面那样的简单解决方案是行不通的.要使 stringWithFormat:@"%C" 工作,您需要输入 0x391 这是 UTF-16 unicode.

Since 0xce91 is in the UTF-8 format and %C expects it to be in UTF-16 a simple solution like the one above won't work. For stringWithFormat:@"%C" to work you need to input 0x391 which is the UTF-16 unicode.

为了从 UTF-8 编码的 unichar 创建一个字符串,您需要首先将 unicode 拆分成它的八位字节,然后使用 initWithBytes:length:encoding.

In order to create a string from the UTF-8 encoded unichar you need to first split the unicode into it's octets and then use initWithBytes:length:encoding.

unichar utf8char = 0xce91; 
char chars[2];
int len = 1;

if (utf8char > 127) {
    chars[0] = (utf8char >> 8) & (1 << 8) - 1;
    chars[1] = utf8char & (1 << 8) - 1; 
    len = 2;
} else {
    chars[0] = utf8char;
}

NSString *string = [[NSString alloc] initWithBytes:chars
                                            length:len 
                                          encoding:NSUTF8StringEncoding];

这篇关于如何在 Objective-C 中将 unichar 值转换为 NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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