GameFreak
GameFreak

Reputation: 2931

How do you convert C String to NSString?

I have been able to find methods like -[NSString stringWithCString:encoding:] but they do not seem to play well when the cstring is a pointer.

Upvotes: 30

Views: 39655

Answers (3)

ThomasW
ThomasW

Reputation: 17317

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

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

Upvotes: 40

Brock Woolf
Brock Woolf

Reputation: 47322

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

Couple of ways you can do this:

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

If you need another encoding like ASCII:

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

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

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

Some other ones you might need:

NSASCIIStringEncoding
NSUnicodeStringEncoding // same as NSUTF16StringEncoding
NSUTF32StringEncoding

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

Upvotes: 44

Chuck
Chuck

Reputation: 237110

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

Upvotes: 12

Related Questions