How can I get the nth character of a string?

147,831

Solution 1

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

Solution 2

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.

Solution 3

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.

Share:
147,831
Aspyn
Author by

Aspyn

Updated on July 10, 2022

Comments

  • Aspyn
    Aspyn almost 2 years

    I have a string,

    char* str = "HELLO"
    

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

  • Graham Perks
    Graham Perks over 12 years
    Well, nuts, I misread. I was going for the "O" instead. Still the answer still applies.
  • Paul
    Paul almost 11 years
    @Aspyn Just for your information, accessing a string like this is fine, but trying to modify it is illegal in C (You can't do str[0] = "J", where str points to a string literal).
  • Sean Letendre
    Sean Letendre over 5 years
    What if the encoding is utf8 and not all characters are ascii?