Convert NSString into char array

后端 未结 6 1629
别那么骄傲
别那么骄傲 2020-11-29 22:53

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?

6条回答
  •  天命终不由人
    2020-11-29 23:24

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

提交回复
热议问题