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.
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.
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.
Tokenizing a string denotes splitting a string with respect to some delimiter(s).
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With