How do I convert a char to an NSString in Objective-C?
Not a null-terminated C string, just a simple char c = 'a'
.
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];
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With