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

问题描述

我在unichar变量中存储了一个国际字符.此字符不是来自文件或URL.变量本身仅存储UTF-8格式的无符号short(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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:52