Split a string in C++
Wed 01 January 2020
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
string a = "";
string b = "ab^cd";
string c = "ab^cd^ef";
char delimiter = '^';
vector<string> aSplit = split(a, delimiter);
vector<string> bSplit = split(b, delimiter);
vector<string> cSplit = split(c, delimiter);
cout << "split a:" << endl;
for (auto it = aSplit.begin(); it < aSplit.end(); ++it) {
cout << *it << endl;
}
cout << "split b:" << endl;
for (auto it = bSplit.begin(); it < bSplit.end(); ++it) {
cout << *it << endl;
}
cout << "split c:" << endl;
for (auto it = cSplit.begin(); it < cSplit.end(); ++it) {
cout << *it << endl;
}
}
Category: Snippets [C++]