Splitting a string by space into array?

Hey. Say I have a string

 
"This is a string"


How do I split it into

 
{"This", "is", "a", "string"}


? This is the equivalent of .split() in Python. Thanks!
C++ has a split() function too, but it's part of boost:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>

int main()
{
    using namespace boost::algorithm;

    std::string str = "This is a string";
    std::vector<std::string> tokens;

    split(tokens, str, is_any_of(" ")); // here it is

    for(auto& s: tokens)
        std::cout << '"' << s << '"' << '\n';
}


But there are plenty of other ways to tokenize a string. For example, using the I/O streams, without any boost:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>

int main()
{
    std::string str = "This is a string";
    std::istringstream buf(str);
    std::istream_iterator<std::string> beg(buf), end;

    std::vector<std::string> tokens(beg, end); // done!

    for(auto& s: tokens)
        std::cout << '"' << s << '"' << '\n';
}
Topic archived. No new replies allowed.