How can I get the nth character of a string?

前端 未结 3 2055
暗喜
暗喜 2020-12-09 17:00

I have a string,

char* str = \"HELLO\"

If I wanted to get just the E from that how would I do that?

相关标签:
3条回答
  • 2020-12-09 17:37
    char* str = "HELLO";
    char c = str[1];
    

    Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

    0 讨论(0)
  • 2020-12-09 17:37

    Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:

    char char_E = str[1];
    char char_L1 = str[2];
    char char_O = str[4];
    

    ...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:

    str = str + 1; // makes it point to 'E' now
    char myChar =  *str;
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-09 17:45

    You would do:

    char c = str[1];
    

    Or even:

    char c = "Hello"[1];
    

    edit: updated to find the "E".

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