Split with string spaces

Asked 1 years ago, Updated 1 years ago, 131 views

In C++, if there's a string with a space, What's the best way to split? Not a quick way, but a good way to look.

c++ split stdstring

2022-09-21 20:23

1 Answers

How about the following?

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s("string to split");
    istringstream iss(s);

    do
    {
        string sub;
        iss >> sub;
        cout << "Substring: " << sub << endl;

    } } while (iss);

}

The other way is to use the standard library

Maybe this is a better code to look.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {
    using namespace std;
    string sentence = "string to split";
    istringstream iss(sentence);

    //To output a word
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         ostream_iterator<string>(cout, "\n"));

    //To save a word to a container
    vector<string> words;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter(words));

    //To create a vector immediately
    vector<string> wordsVector{istream_iterator<string>{iss},
                      istream_iterator<string>{}};
}


2022-09-21 20:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.