Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 568
user3247278 Avatar asked Dec 15 '22 19:12

user3247278


1 Answers

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."
like image 137
Vlad from Moscow Avatar answered Dec 27 '22 19:12

Vlad from Moscow