views:

39

answers:

2

I want to get the characters of an NSString. Like this:

NSString *data;
const char * typein = [[data characters] UTF8String];

But obviously NSString won't respond to -characters. How do I get the characters of NSString?

thanks, Elijah

+3  A: 

You can use this function:

for(int i =0 ;i<[myString length]; i++) {
  char = [myString characterAtIndex:i];
}

or

NSString *str = @"astring";
const char *cString = [str UTF8String];
mklfarha
`-[NSString cString]` has been deprecated for ages; you should be using `-[NSString UTF8String]` or `-[NSString cStringUsingEncoding:]`.
Wevah
i didn't know that thank you - i am going to modify my answer
mklfarha
Corrected, this is the better answer, though it doesn't explain why. While `-UTF8String` works to get a buffer, you'll need to use `characterAtIndex:` if you want the fully composed unicode characters, some of which may be multiple bytes.
bbum
With these corrections I'm with bbum.
Abizern
+3  A: 

If you just want to get a cString from the NSString just call UTF8String as you are already doing and then iterate the array.

Abizern
Note that this gets a reference to a buffer containing the raw string. As long as it is ASCII, it'll be one byte per character. If it is unicode, it quite likely will contain characters that span multiple bytes.
bbum