Splitting a C++ std::string using tokens, e.g. ";" [duplicate]
Matthew Harrington
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.
23 Answers
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); }
} 2 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;
} 5 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";
}