How do I split a string into an array by spaces?

My program requires that I can split any random string (sentence) into vector of strings by white space.

So if I have the string: "I like to code"

Then my program will split it by white space and put it in a vector:

[I, like, to, code]

I've been trying to find the function for this, but am unable to find one.
Using a string stream:

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

std::vector<std::string> split_ws( std::string str )
{
    std::vector<std::string> result ;

    std::istringstream stm(str) ; // http://www.artima.com/cppsource/streamstrings3.html
    std::string token ;
    while( stm >> token ) result.push_back(token) ;
    // could use std::istream_iterator<std::string> instead

    return result ;
}

int main()
{
    for( std::string s : split_ws( "I like to code" ) ) std::cout << s << '\n' ;
}

http://coliru.stacked-crooked.com/a/a199743d3fba3b9e
Topic archived. No new replies allowed.