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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |