I have a string,
char* str = "HELLO"
If I wanted to get just the E
from that how would I do that?
I have a string,
char* str = "HELLO"
If I wanted to get just the E
from that how would I do that?
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
C
(You can't do str[0] = "J"
, where str
points to a string literal). –
Mesne 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.
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
C
(You can't do str[0] = "J"
, where str
points to a string literal). –
Mesne 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.
© 2022 - 2024 — McMap. All rights reserved.