Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a space separated string into multiple strings in C++?

Tags:

c++

string

stream

Somewhat my code looks like below:

static int myfunc(const string& stringInput)
{
    string word;
    stringstream ss;

    ss << stringInput;
    while(ss >> word)
    {
        ++counters[word];
    }
    ...
}

The purpose here is to get an input string (separated by white space ' ') into the string variable word, but the code here seems to have a lot of overhead -- convert the input string to a string stream and read from the string stream into the target string.

Is there a more elegant way to accomplish the same purpose?

like image 985
Qiang Xu Avatar asked Jan 18 '23 22:01

Qiang Xu


1 Answers

You are asking how to split a string. Boost has a helpful utility boost::split()

http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

Here's an example that puts the resulting words into a vector:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));
like image 150
alex tingle Avatar answered Jan 27 '23 10:01

alex tingle