Last active
February 24, 2019 03:32
-
-
Save GenesisFR/73573732bd9ad8411a8e1fb0b8f74ba9 to your computer and use it in GitHub Desktop.
C++ function to split strings
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 <sstream> | |
#include <vector> | |
using namespace std; | |
vector<string> split(const string &s, char delimiter = ',', bool includeEmpties = true) | |
{ | |
vector<string> tokens; | |
string token; | |
istringstream tokenStream(s); | |
while (!tokenStream.eof()) | |
{ | |
getline(tokenStream, token, delimiter); | |
if (!includeEmpties && token.empty()) | |
continue; | |
tokens.push_back(token); | |
} | |
return tokens; | |
} | |
vector<string> split(const string &s, string delim = " ") | |
{ | |
vector<string> splitString; | |
int startIndex = 0; | |
int endIndex = 0; | |
while ((endIndex = s.find(delim, startIndex)) < s.size()) | |
{ | |
string val = s.substr(startIndex, endIndex - startIndex); | |
splitString.push_back(val); | |
startIndex = endIndex + delim.size(); | |
} | |
if (startIndex < s.size()) | |
{ | |
string val = s.substr(startIndex); | |
splitString.push_back(val); | |
} | |
return splitString; | |
} | |
int main() | |
{ | |
vector<string> vect = split("hello,world", ','); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment