Created
March 22, 2018 23:11
-
-
Save quedlin/bf65ccb07970fc4256647fb6981eaa3e to your computer and use it in GitHub Desktop.
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
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