Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSString to C string?

Tags:

objective-c

I know that this question is a possible duplicate, but even after looking at some Google tutorials and questions even on this forum none of them gives me a decent answer about this subject.

I have:

NSString *str = @"text"; 

And I would like to do something like:

char cstring [512] = str; 

(this only shows what I want to do, after looking at Apple's NSString Class Ref I didn't even think about using it).

Up to now I have:

char command [512] = [[NSString stringWithFormat:@"text"] cStringUsingEncoding:NSUTF8StringEncoding]; 

Still, with that I get errors.

Any solution?

like image 955
Matoe Avatar asked Jul 14 '11 02:07

Matoe


People also ask

How to convert NSString to string?

To convert NSString to const char use -[NSString UTF8String] : NSString *myNSString = @"Some string"; const char *cString = [myNSString UTF8String]; You could also use -[NSString cStringUsingEncoding:] if your string is encoded with something other than UTF-8.

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

How do I append to NSString?

Working with NSString. Instances of the class NSString are immutable – their contents cannot be changed. Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.


2 Answers

try const char *command = [str UTF8String];

like image 193
Jesus Ramos Avatar answered Oct 07 '22 20:10

Jesus Ramos


A c string is returned as a pointer, not as an array of characters. To use it, you can change your variable to a pointer.

const char *command = [theString cStringUsingEncoding:NSUTF8StringEncoding]; 

Since you want the UTF8 encoding, you can use the UTF8String convenience method.

const char *command = [theString UTF8String]; 

If you need the data to be stored in a character array, you can use the getCString:maxLength:encoding: method, passing the array as the buffer. This will allow you to store the string directly to the buffer, and will tell you if the buffer is too small.

char command[512]; if(![theString getCString:command maxLength:sizeof(command)/sizeof(*command) encoding:NSUTF8StringEncoding]) {     NSLog(@"Command buffer too small"); } 
like image 22
ughoavgfhw Avatar answered Oct 07 '22 19:10

ughoavgfhw