How to convert a string to character array in c (or) how to extract a single char form string?

前端 未结 3 1714
生来不讨喜
生来不讨喜 2020-12-15 07:12

I need to convert a string to a char array in C; how can I do this?

Or at least, how can I extract single chars from a string incrementally?

相关标签:
3条回答
  • 2020-12-15 07:28

    In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

    Therefore, to extract a character c at index i from string your_string, just use

    char c = your_string[i];
    

    Index is base 0 (first character is your_string[0], second is your_string[1]...).

    0 讨论(0)
  • 2020-12-15 07:32

    In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,

    char myString[] = "This is some text";
    

    You can access any character as a simple char by using myString as an array, thus:

    char myChar = myString[6];
    printf("%c\n", myChar); // Prints s
    

    Hope this helps! David

    0 讨论(0)
  • 2020-12-15 07:38

    In this simple way

    char str [10] = "IAmCute";
    printf ("%c",str[4]);
    
    0 讨论(0)
提交回复
热议问题