In C++, there is no inbuilt split method for string. It is very useful to split a string into a vector of string. We can use the following string split method to split a string into a vector or string using the stringstream class.
vector<string> split(const string& text) {
string tmp;
vector<string> stk;
stringstream ss(text);
while(getline(ss,tmp,' ')) {
stk.push_back(tmp);
}
return stk;
}
Example usage:
int main() {
string str = "This is me";
vector<string> words = split(str);
// words = ["This", "is", "me"];
for (const auto &n: words) {
cout << n << endl;
}
}
And of course, you can easily add the support for custom delimiter such as split a string by comma or colon (IP addresses):
vector<string> split(const string& text, char delimiter) {
string tmp;
vector<string> stk;
stringstream ss(text);
while(getline(ss,tmp, delimiter)) {
stk.push_back(tmp);
}
return stk;
}
Another C++ string split implementation
Here is another C++ split implementation that goes through each character and split it by the delimiter.
vector<string> split(string path, char d) {
vector<string> r;
int j = 0;
for (int i = 0; i < path.length(); i ++) {
if (path[i] == d) {
string cur = path.substr(j, i - j);
if (cur.length()) {
r.push_back(cur);
}
j = i + 1;
}
}
if (j < path.length()) {
r.push_back(path.substr(j));
}
return r;
}
Let’s hope that a string split function will be added to the string class in future C++ releases!
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: The Best Instagram Feed WordPress Plugins to Use
Next Post: 3 Reasons Why Graphic Designers Need to Self-Promote through Instagram