Last active
September 8, 2015 03:15
-
-
Save dongguosheng/9067874 to your computer and use it in GitHub Desktop.
C++ utils
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
#include <string> | |
#include <vector> | |
#include <sstream> | |
using std::vector; | |
using std::string; | |
using std::stringstream; | |
vector<string> &split(const string &s, char delim, vector<string> &result) { | |
stringstream ss(s); | |
string item; | |
while (std::getline(ss, item, delim)) { | |
result.push_back(item); | |
} | |
return result; | |
} | |
vector<string>& split(const string &s, const string &delim, vector<string> &result) { | |
if(s.empty()) return result; | |
if(s.size() < delim.size() || delim.empty()) { | |
result.push_back(s); | |
return result; | |
} | |
size_t start_index = 0, find_index; | |
while(true) { | |
find_index = s.find(delim, start_index); | |
if(find_index == string::npos) { | |
result.push_back(s.substr(start_index, s.size() - start_index)); | |
break; | |
} else { | |
result.push_back(s.substr(start_index, find_index - start_index)); | |
start_index = find_index + delim.size(); | |
if(start_index == s.size()) { | |
result.push_back(""); | |
break; | |
} | |
if(start_index > s.size()) break; | |
} | |
} | |
return result; | |
} | |
template<typename T> | |
vector<string> split(const string &s, T &delim) { | |
vector<string> result; | |
split(s, delim, result); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
split(" ac c d", ' ') => ["ac", " ", "c", "d"]