Reputation:
I have something like:
NSString *str = "hello this is 123.";
I want it to be placed into a char array, so I can read it character by character.
So it would be like:
charArray[0] = 'h'
charArray[1] = 'e'
charArray[2] = 'l'
and so on..
How can I convert a string to a char array and how can I read each cell of the char array?
Upvotes: 3
Views: 8259
Reputation: 9688
Try something like this, and note that it's a capital C, which really screwed me up with special characters.
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
[array addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
}
Upvotes: 4
Reputation: 12710
Nsstring may contain utf 8 or utf 16 character which can't fit in a char, so it may be a bad idea to access the underlying char array.
If you wan't you can use the characterAtIndex message to access a given character and iterate over the string.
Upvotes: 1
Reputation: 1480
NSString *s = @"hello this is 123.";
const char *c = [s UTF8String];
You could also use -[NSString cStringUsingEncoding:] if your string is encoded with something other than UTF-8.
Upvotes: 3