0

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!

0

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Doesn't this do the same thing as buffer = [schoolName cStringUsingEncoding: NSUTF8StringEncoding];?
I've never used cStringUsingEncoding but I use UTF8String quite regularly and I've never seen it not be NULL terminated.
I'm sorry, your answer IS NOT INCORRECT, but I fear that I have wrote my QUESTION wrong! I need to do the exact opposite, IE, I need to turn my Objective-C object INTO C. I'm really sorry about the mistake.
I'm sorry, but my answer was absolutely correct for the question you posted!
Shorter: [NSString stringWithUTF8String:cstring], or the new Clang "boxed expression", NSString *nsstring = @(cstring).
|
3
NSString* str = [NSString stringWithUTF8String:(const char *)]

or

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

or

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

Comments

1

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;
};

1 Comment

I appreciate the answer, but as listed above, there is a slightly easier way of doing it. Up-vote for an answer that works, and for not being afraid to use a lot of cod.e

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.