Objective-C Language NSString Working with C Strings


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.

For the reverse path use -[NSString stringWithUTF8String:]:

const *char cString = "Some string";
NSString *myNSString = [NSString stringWithUTF8String:cString];
myNSString = @(cString); // Equivalent to the above.

Once you have the const char *, you can work with it similarly to an array of chars:

printf("%c\n", cString[5]);

If you want to modify the string, make a copy:

char *cpy = calloc(strlen(cString)+1, 1);
strncpy(cpy, cString, strlen(cString));
// Do stuff with cpy