简体   繁体   中英

string to char array

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?

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]]];
}
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM