Casting or converting a char to an NSString in Objective-C

老子叫甜甜 提交于 2019-12-05 09:00:42

问题


How do I convert a char to an NSString in Objective-C?

Not a null-terminated C string, just a simple char c = 'a'.


回答1:


You can use stringWithFormat:, passing in a format of %c to represent a character, like this:

char c = 'a';
NSString *s = [NSString stringWithFormat:@"%c", c];



回答2:


You can make a C-string out of one character like this:

char cs[2] = {c, 0}; //c is the character to convert
NSString *s = [[NSString alloc] initWithCString:cs encoding: SomeEncoding];

Alternatively, if the character is known to be an ASCII character (i. e. Latin letter, number, or a punctuation sign), here's another way:

unichar uc = (unichar)c; //Just extend to 16 bits
NSString *s = [NSString stringWithCharacters:&uc length:1];

The latter snippet with surely fail (not crash, but produce a wrong string) with national characters. For those, simple extension to 16 bits is not a correct conversion to Unicode. That's why the encoding parameter is needed.

Also note that the two snippets above produce a string with diferent deallocation requirements. The latter makes an autoreleased string, the former makes a string that needs a [release] call.



来源:https://stackoverflow.com/questions/5134663/casting-or-converting-a-char-to-an-nsstring-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!