Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 580
venkysmarty Avatar asked Mar 02 '11 12:03

venkysmarty


People also ask

Does C++ have a string split function?

There is no built-in split() function in C++ for splitting string but many multiple ways exist in C++ to do the same task, such as using getline() function, strtok() function, using find() and erase() functions, etc.

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What is Tokenizing a string in C++?

Tokenizing a string denotes splitting a string with respect to some delimiter(s).


1 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);     } } 
like image 160
Martin Stone Avatar answered Sep 18 '22 17:09

Martin Stone