Separation of C ++ std :: string using tokens, for example. ";"

Possible duplicate:
How to split a string in C ++?

Best way to break a string in C ++? It can be assumed that the string consists of words separated;

From our point of view, C string functions are not allowed, and Boost is also not allowed, since for security reasons open source is prohibited.

The best solution I have now is:

string str ("Denmark; Sweden; India; USA");

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

Thanks for the input.

+62
c ++
Mar 02 2018-11-12T00:
source share
3 answers

I find std::getline() often the easiest. The optional delimiter parameter means that it is 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); } } 
+144
Mar 02 2018-11-12T00:
source share

You can use a stream of strings and read elements into a vector.

There are many different examples ...

Copy of one example:

 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; } 
+11
Mar 02 '11 at 12:44
source share

There are several libraries that solve this problem, but the simplest is probably to use the 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"; } 
+10
Mar 02 2018-11-11T00:
source share



All Articles