string split in c++ stl code example
Example 1: tokenize string c++
std::vector<std::string> tokenise(const std::string &str){
std::vector<std::string> tokens;
int first = 0;
while(first<str.size()){
int second = str.find_first_of(',',first);
if(second==std::string::npos){
second = str.size();
}
std::string token = str.substr(first, second-first);
tokens.push_back(token);
first = second + 1;
}
return tokens;
}
Example 2: c++ string split
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
Example 3: split in c++
std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;