galois galois - 2 months ago 9
C++ Question

Treat c++ string as a pointer

How can the STL and

std::string
instead of
char*
be used to go about jumping around a string like this (admittedly nonsensical) example?

char* s = "XXXXXXXXhello";
while (*s == 'X')
s++;

s += 2;
std::cout << ----s; //prints `hello`

Answer

If what you want to do is modify the object, and get rid of "h":

std::string s = "hello";
s = s.substr(1); // position = 1, length = everything (npos)
std::cout << s;  //"ello"

or

std::string s = "hello";
s.erase(0, 1); // position = 0, length = 1
std::cout << s;  //"ello"