3

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?

3 Answers 3

4

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]]];
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly what I was searching for. Thank you!
3
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.

1 Comment

how can I print each cell to output? lookin for something like: NSLog(@"the 1st char is %@", char[0]); but it doesn't work.
1

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.

1 Comment

This is how I'd go about it, instead of assuming.

Your Answer

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