Skip to content

Instantly share code, notes, and snippets.

@quedlin
Created March 22, 2018 23:11
Show Gist options
  • Save quedlin/bf65ccb07970fc4256647fb6981eaa3e to your computer and use it in GitHub Desktop.
Save quedlin/bf65ccb07970fc4256647fb6981eaa3e to your computer and use it in GitHub Desktop.
I use this to split string by a delimiter. The first puts the results in a pre-constructed vector, the second returns a new vector.
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:
std::vector<std::string> x = split("one:two::three", ':');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment