Reputation: 227
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
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
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
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