How to remove first word from a string?

user3247278 picture user3247278 · Oct 1, 2014 · Viewed 14.6k times · Source

Let's say I have

string sentence{"Hello how are you."}

And I want string sentence to have "how are you" without the "Hello". How would I go about doing that.

I tried doing something like:

stringstream ss(sentence);
ss>> string junkWord;//to get rid of first word

But when I did:

cout<<sentence;//still prints out "Hello how are you"

It's pretty obvious that the stringstream doesn't change the actual string. I also tried using strtok but it doesn't work well with string.

Answer

Vlad from Moscow picture Vlad from Moscow · Oct 1, 2014

Try the following

#include <iostream>
#include <string>

int main() 
{
    std::string sentence{"Hello how are you."};

    std::string::size_type n = 0;
    n = sentence.find_first_not_of( " \t", n );
    n = sentence.find_first_of( " \t", n );
    sentence.erase( 0,  sentence.find_first_not_of( " \t", n ) );

    std::cout << '\"' << sentence << "\"\n";

    return 0;
}

The output is

"how are you."