Casting or converting a char to an NSString in Obj

2019-04-03 09:34发布

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

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

2条回答
Evening l夕情丶
2楼-- · 2019-04-03 09:50

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.

查看更多
祖国的老花朵
3楼-- · 2019-04-03 09:53

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];
查看更多
登录 后发表回答