Next: NSMutableString Up: NSString Previous: stringWithFormat

Converting to and from C strings

It is often useful to be able to create a NSString from a standard ASCII 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 +stringWithCString:, as follows:
char *result;
NSString *string;

result = function ();
string = [NSString stringWithCString: result];
Sometimes we need to do the reverse, i.e. to convert a NSString to a standard C ASCII string. We can do it using the -cString method of the NSString class, as in the following example:
char *result;
NSString *string;

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



Nicola 2002-01-13