Math-Linux.com

Knowledge base dedicated to Linux and applied mathematics.

Home > C++ > FAQ C++ > FAQ C++ - STL > How to split a string in C++ using STL ?

How to split a string in C++ using STL ?

What’s the most elegant way to split a string in C++? The string can be assumed to be composed of words separated by whitespace.

Here’s a 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 = "Something in the way she moves...";
    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<vector<string> >(tokens));

Original link:http://stackoverflow.com/questions/236129

Author Question:
http://stackoverflow.com/users/1630

Author Anwser:
http://stackoverflow.com/users/30767

Also in this section

  1. How to print the elements of a C++ std::vector with GNU Debugger GDB ?
  2. How to convert string to lower case or UPPER case in C++ ?
  3. How to get command-line parameters in a C++ vector<string> ?
  4. How to split a string in C++ using STL ?
  5. How to sum elements of a C++ std::vector ?