Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a variable of type char[] and I want to copy NSString value in it. How can I convert an NSString to a char array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
866 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
", 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...