Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert cstring to NSString?

Tags:

cocoa

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.

like image 462
GameFreak Avatar asked Feb 04 '09 01:02

GameFreak


People also ask

How to convert NSString to const char?

To convert NSString to const char use -[NSString UTF8String] : NSString *myNSString = @"Some string"; const char *cString = [myNSString UTF8String]; You could also use -[NSString cStringUsingEncoding:] if your string is encoded with something other than UTF-8.

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.


1 Answers

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)

like image 137
Brock Woolf Avatar answered Sep 28 '22 05:09

Brock Woolf