Programming Tutorials
Perfect C++ String Explode Split
Ever wanted the perfect explode or split using the C++ std::string class? Where you can split a string based on a delimiter or separator and store the results in a vector? Here's an easy way to do it!
There were many options available online, but this seemed to be the best way to do it.
void StringExplode(string str, string separator, vector<string>* results){ int found; found = str.find_first_of(separator); while(found != string::npos){ if(found > 0){ results->push_back(str.substr(0,found)); } str = str.substr(found+1); found = str.find_first_of(separator); } if(str.length() > 0){ results->push_back(str); } }
Using the std::string function "find_first_of" we get the first instance of separator and store it into found integer.
We then check string::npos and compare with found, so that we make sure our while loop doesn't end until we have reached string::npos (the maximum position of a string index).
If we find an instance, we store it into a std::vector called "results".
Of course we need to update found integer. We also need a solution for the last area, which we push into our results after the while loop.
Here's how to use it:
vector<string> R; string thisstring = "Inferno Development is a great programming community and tutorial site"; StringExplode(thisstring, " ", &R); // vector R now contains each word!
Don't forget to include your headers:
#include <vector> #include <string>
Hopefully this will help many of you with your short small programs dealing with strings. String Explode is a great technique similar to PHP's explode() function and Java's string.split() method.


Post new comment