Use -[NSString UTF8String]
:
NSString *s = @"Some string";
const char *c = [s UTF8String];
You could also use -[NSString cStringUsingEncoding:]
if your string is encoded with something other than UTF-8.
Once you have the const char *
, you can work with it similarly to an array of chars
:
printf("%c\n", c[5]);
If you want to modify the string, make a copy:
char *cpy = calloc([s length]+1, 1);
strncpy(cpy, c, [s length]);
// Do stuff with cpy
free(cpy);
mipadi's answer is the best if you just want a char*
containing the contents of the string, however NSString provides methods for obtaining the data into a buffer that you have allocated yourself. For example, you can copy the characters into an array of unichar
using getCharacters:range:
like this:
NSUInteger length = [str length];
unichar buffer[length];
[str getCharacters:buffer range:NSMakeRange(0, length)];
for (NSUInteger i = 0; i < length; i++)
{
doSomethingWithThis(buffer[i]);
}
If you have to use char
, then you can use the more complicated getBytes:maxLength:usedLength:encoding:options:range:remainingRange:
like this (demonstrated in Eastern Polish Christmas Tree notation):
NSUInteger length = [str length];
NSUInteger bufferSize = 500;
char buffer[bufferSize] = {0};
[str getBytes:buffer
maxLength:(bufferSize - 1)
usedLength:NULL
encoding:NSUTF8StringEncoding
options:0
range:NSMakeRange(0, length)
remainingRange:NULL];
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
[array addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
}
Rather than getCharacters:range:
, I use:
[stringToCopy getCString:c_buffer maxLength:c_buffer_length encoding:NSUTF8StringEncoding];
The result is a char[] (instead of unichar[]), which is what the OP was wanting, and what you probably want to use for C compatibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With