Next: 1.5 NSMutableString Up: 1 NSString Previous: 1.3 stringWithFormat

1.4 Converting to and from C strings

It is often useful to be able to create a NSString from a standard ASCII (or more generally UTF-8) C string (not fixed at compile time). Say for example that our program needs to call a C library function
char *function (void);
which returns some useful information in a C string. We want to create a NSString using the contents of the C string. The simplest way to do it is by using the NSString's class method +stringWithUTF8String:, as follows:
char *result;
NSString *string;

result = function ();
string = [NSString stringWithUTF8String: result];
Sometimes we need to do the reverse, i.e. to convert a NSString to a standard C ASCII (or more generally UTF-8) string. We can do it using the -UTF8String method of the NSString class, as in the following example:

char *result;
NSString *string;

string = @"Hello";
result = [string UTF8String];