How to convert NSString to C string?

后端 未结 2 1242
刺人心
刺人心 2021-02-03 18:27

I know that this question is a possible duplicate, but even after looking at some Google tutorials and questions even on this forum none of them gives me a decent answer about t

相关标签:
2条回答
  • 2021-02-03 19:11

    A c string is returned as a pointer, not as an array of characters. To use it, you can change your variable to a pointer.

    const char *command = [theString cStringUsingEncoding:NSUTF8StringEncoding];
    

    Since you want the UTF8 encoding, you can use the UTF8String convenience method.

    const char *command = [theString UTF8String];
    

    If you need the data to be stored in a character array, you can use the getCString:maxLength:encoding: method, passing the array as the buffer. This will allow you to store the string directly to the buffer, and will tell you if the buffer is too small.

    char command[512];
    if(![theString getCString:command maxLength:sizeof(command)/sizeof(*command) encoding:NSUTF8StringEncoding]) {
        NSLog(@"Command buffer too small");
    }
    
    0 讨论(0)
  • 2021-02-03 19:17

    try const char *command = [str UTF8String];

    0 讨论(0)
提交回复
热议问题