Sir_Mr_Bman
Sir_Mr_Bman

Reputation: 227

How to convert Objective-C string into a C string?

I need to convert an C-String into an NSString.
How do I do this?
I know how to convert it the OTHER WAY,

NSString *hello = @"Hello!";
const char *buffer;
buffer = [schoolName cStringUsingEncoding: NSUTF8StringEncoding];
NSLog(@"C-String is: %s", buffer);

However, how do I do it Objective-C string (NSString) into a NULL-TERMINATED string.

Thanks!

Upvotes: 0

Views: 730

Answers (3)

Ron
Ron

Reputation: 1269

NSString* str = [NSString stringWithUTF8String:(const char *)]

or

NSString* str = [NSString stringWithCString:(const char *) encoding:(NSStringEncoding)]

or

NSString* str = [NSString stringWithCharacters:(const unichar *) length:(NSUInteger)]

Upvotes: 3

Nikos M.
Nikos M.

Reputation: 13783

Try something like this:

- (wchar_t*)getWideString
{
    const char* temp = [schoolName cStringUsingEncoding:NSUTF8StringEncoding];
    int buflen = strlen(temp)+1; //including NULL terminating char
    wchar_t* buffer = malloc(buflen * sizeof(wchar_t));
    mbstowcs(buffer, temp, buflen);
    return buffer;
};

Upvotes: 1

mah
mah

Reputation: 39847

const char *buffer = [hello UTF8String]; will do what you're looking for.

Now to answer the new (and very different) question:

If you have, for example, const char *cstring = "hello world"; you can create an NSString * with it through: NSString *nsstring = [NSString stringWithFormat:@"%s", cstring];

There are, of course, other ways to accomplish the same thing.

Upvotes: 7

Related Questions