I was really amazed to find out that C++ string class has no split method. There are plenty of accasions I needed to split a string by a given delimiter. Lets see how to split a string and put substrings in a to vector.
vector<string> split(const string &str, const char delim) { | |
vector<string> tokens; | |
string::size_type start = 0; | |
string::size_type end = 0; | |
while ((end = str.find(delim, start)) != string::npos) { | |
tokens.push_back(str.substr(start, end - start)); | |
start = end + 1; | |
} | |
tokens.push_back(str.substr(start)); | |
return tokens; | |
} |
vector<string> split(const string &str, const char delim) { | |
vector<string> tokens; | |
string::size_type start = 0; | |
string::size_type end = 0; | |
while ((start = str.find_first_not_of(delim, end)) != string::npos) { | |
end = str.find(delim, start); | |
tokens.push_back(str.substr(start, end - start)); | |
} | |
return tokens; | |
} |