Search code examples
c++stringstringstreamstrtok

How to remove first word from a string?


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.


Solution

  • str=str.substr(str.find_first_of(" \t")+1);
    

    Tested:

    string sentence="Hello how are you.";
    cout<<"Before:"<<sentence<<endl;
    sentence=sentence.substr(sentence.find_first_of(" \t")+1);
    cout<<"After:"<<sentence<<endl;
    

    Execution:

    > ./a.out
    Before:Hello how are you.
    After:how are you.
    

    Assumption is the line does not start with an empty space. In such a case this does not work.

    find_first_of("<list of characters>").
    

    the list of characters in our case is space and a tab. This will search for first occurance of any of the list of characters and return an iterator. After that adding +1 movers the position by one character.Then the position points to the second word of the line. Substr(pos) will fetch the substring starting from position till the last character of the string.