Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 926
Senkwe Avatar asked Feb 27 '11 17:02

Senkwe


People also ask

How to convert char to NSString in Objective c?

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

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


2 Answers

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]; 
like image 198
BoltClock Avatar answered Sep 23 '22 17:09

BoltClock


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.

like image 40
Seva Alekseyev Avatar answered Sep 22 '22 17:09

Seva Alekseyev