1 使用stringstream
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string str, char separator) {
vector<string> res;
stringstream ss(str);
string t;
while (getline(ss, t, separator)) {
res.emplace_back(t);
}
return res;
}
int main() {
string str = "../../Hello_World_I_am_a_string";
vector<string> vec = split(str, '_');
for (auto x : vec) {
cout << x << endl;
}
return 0;
}
2 使用双指针算法
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string str, char separator) {
vector<string> res;
for (int i = 0, j = 0; i < str.size(); ++i) {
j = i;
while (j < str.size() && str[j] != separator) {
j++;
}
string t = str.substr(i, j-i);
res.emplace_back(t);
i = j;
}
return res;
}
int main() {
string str = "../../Hello_World_I_am_a_string";
vector<string> vec = split(str, '_');
for (auto x : vec) {
cout << x << endl;
}
return 0;
}