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

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

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 concerns 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.


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);
    }
}

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;
}

有几个库可以解决这个问题,但最简单的可能是使用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";
}
链接地址: http://www.djcxy.com/p/19562.html

上一篇: 按单个空格拆分字符串

下一篇: 使用标记分割C ++ std :: string,例如“;”