caesar
caesar

Reputation: 3125

c++ splitting a string and getting the part coming after whitespace

I need to do a string splitting such that If I have a string like below

string foo="thisIsThe         Test     Input";

I need to get the part coming after the multiple or single withspace. In this case I need to get "Test Input". I know that I can get the first part by :

int index=foo.find(' ');
string subString=foo.substr(0,index);

But I dont know how could I do what I want. Is there anyone to help me ?

Upvotes: 0

Views: 134

Answers (2)

Quaxton Hale
Quaxton Hale

Reputation: 2520

You can also copy to a new string char by char eliminating any spaces too. It will make it easier to use foo.find(' ');

Eliminate all whitespace

string foo = "thisIsThe         Test     Input";
string bar[100];

for (int i = 0; i < foo.length(); i++)
{
    if (foo[i] != ' ')
        bar[i] = foo[i];


}
for (int i = 0; i < sizeof(bar) / sizeof(bar[i]); i++)
    cout << bar[i];

Keep one space between each term:

string foo = "thisIsThe         Test     Input";
    string bar[100];

    for (int i = 0; i < foo.length(); i++)
    {
        if (foo[i] != ' ')
            bar[i] = foo[i];

        else if (foo[i + 1] != ' ' && foo[i] == ' ')
            bar[i] = ' ';

    }
    for (int i = 0; i < sizeof(bar)/sizeof(bar[i]); i++)


cout << bar[i];

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283624

std::find_first_not_of accepts a position argument which indicates where to start searching. So use that to find the first non-space, starting at the first space.

int index=foo.find(' ');
index=foo.find_first_not_of(' ', index);
string subString=foo.substr(index);

Upvotes: 1

Related Questions