[ACCEPTED]-How do you convert cstring to NSString?-cocoa

Accepted answer
Score: 40

First up, don't use initWithCString, it has been deprecated.

Couple 10 of ways you can do this:

const *char cString = "Hello";
NSString *myNSString = [NSString stringWithUTF8String:cString];

If you need another 9 encoding like ASCII:

const *char cString = "Hello";
NSString *myNSString = [NSString stringWithCString:cString encoding:NSASCIIStringEncoding];

If you want to see all 8 the string encodings available, in Xcode, hold 7 command + option then double click on NSASCIIStringEncoding in the above code block.

You will 6 be able to see where Apple have declared 5 their enumeration for the string encoding 4 types. Bit quicker than trying to find it 3 in the documentation.

Some other ones you 2 might need:

NSUnicodeStringEncoding // same as NSUTF16StringEncoding

Checkout Apple's NSString Class Reference (encodings 1 are at the bottom of the page)

Score: 35

With modern Objective-C (since Xcode 5 at 1 least) you can just do:

char const* cString = "Hello";
NSString *myNSString = @(cString);
Score: 12

stringWithCString:encoding: creates an NSString from a given C string. To 3 create a C string from an NSString, use 2 either the UTF8String method (generally preferred) or 1 cStringUsingEncoding: (if you need an encoding other than UTF-8).

More Related questions