String split in C++
Contents
Split string
- use
getline
andstringstream
std::vector<std::string> split(const std::string& in, char delimiter){
std::stringstream ss(in);
vector<std::string> tokens;
std::string token;
while(std::getline(ss,token,delimiter)){
tokens.push_back(token);
}
return tokens;
}
- use the
std::string::find()
function to find the position of your string delimiter, then usestd::string::substr()
to get a token. in this case, the delimiter can be a string that would be more useful when handling delimiters that are longer than one character.
std::vector<std::string> split(const std::string& s, std::string delimiter){
std::vector<std::string> tokens;
size_t pos = 0;
size_t start = 0;
while( (pos = s.find(delimiter, start)) != std::string::npos){
tokens.push_back(s.substr(start,pos););
start = pos + delimiter.length();
}
// last token
tokens.push_back(s.substr(start));
return tokens;
}