Splitting a C++ std::string using tokens, e.g. ";"

C++

C++ Problem Overview


> Possible Duplicate:
> How to split a string in C++?

Best way to split a string in C++? The string can be assumed to be composed of words separated by ;

From our guide lines point of view C string functions are not allowed and also Boost is also not allowed to use because of security conecerns open source is not allowed.

The best solution I have right now is:

string str("denmark;sweden;india;us");

Above str should be stored in vector as strings. how can we achieve this?

Thanks for inputs.

C++ Solutions


Solution 1 - C++

I find std::getline() is often the simplest. The optional delimiter parameter means it's not just for reading "lines":

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings;
    istringstream f("denmark;sweden;india;us");
    string s;    
    while (getline(f, s, ';')) {
        cout << s << endl;
        strings.push_back(s);
    }
}

Solution 2 - C++

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
{
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );
    
        output.push_back(substring);
    
        prev_pos = ++pos;
    }

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;
}

Solution 3 - C++

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvenkysmartyView Question on Stackoverflow
Solution 1 - C++Martin StoneView Answer on Stackoverflow
Solution 2 - C++Fox32View Answer on Stackoverflow
Solution 3 - C++hkaiserView Answer on Stackoverflow