ProAnswers.org

How to split a string in C++ ?

I use this to split string by a delim. The first puts the results in an already constructed vector, the second returns a new vector.

std::vector &split(const std::string &s, char delim, std::vector &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}

std::vector split(const std::string &s, char delim) {
std::vector elems;
return split(s, delim, elems);
}