Search code examples
c++stringsplit

How do I iterate over the words of a string?


How do I iterate over the words of a string composed of words separated by whitespace?

Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:

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

using namespace std;

int main() {
    string s = "Somewhere down the road";
    istringstream iss(s);

    do {
        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);
}

Solution

  • For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    
    int main() {
        using namespace std;
        string sentence = "And I feel fine...";
        istringstream iss(sentence);
        copy(istream_iterator<string>(iss),
             istream_iterator<string>(),
             ostream_iterator<string>(cout, "\n"));
    }
    

    Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic copy algorithm.

    vector<string> tokens;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter(tokens));
    

    ... or create the vector directly:

    vector<string> tokens{istream_iterator<string>{iss},
                          istream_iterator<string>{}};