// Splits a string based on another string and returns vector of substrings.
// vector<string> substrings = split("123.23.111.89",".") returns
// "123", "23", "111" and "89"
vector<string> split(string str, string delim, bool ignoreEmptyTokens = true) {
vector<string> strings;
size_t pos = 0;
string token;
while ((pos = str.find(delim)) != string::npos) {
token = str.substr(0, pos);
if (token == "") {
if (!ignoreEmptyTokens) {
strings.push_back(token);
}
}
else {
strings.push_back(token);
}
str.erase(0, pos + delim.length());
}
if (strlen(str.c_str()) > 0) {
strings.push_back(str);
}
return strings;
}
Posted: March 20, 2023
Return to the snippets listing