How can I get the nth character of a string?
Asked Answered
F

3

22

I have a string,

char* str = "HELLO"

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

Felicidadfelicie answered 10/12, 2011 at 3:47 Comment(0)
A
18

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

Alitta answered 10/12, 2011 at 3:49 Comment(2)
Well, nuts, I misread. I was going for the "O" instead. Still the answer still applies.Alitta
@Felicidadfelicie 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).Mesne
R
30
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.

Rambling answered 10/12, 2011 at 3:53 Comment(1)
What if the encoding is utf8 and not all characters are ascii?Wadai
A
18

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

Alitta answered 10/12, 2011 at 3:49 Comment(2)
Well, nuts, I misread. I was going for the "O" instead. Still the answer still applies.Alitta
@Felicidadfelicie 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).Mesne
R
5

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.

Retentive answered 10/12, 2011 at 5:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.