C++的string没有spilt的功能,本文通过使用Sting的find和substr方法实现spilt的功能
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void spilt(vector<string> &s, string str, string delimiter) {
int index(0);
while (str.find(delimiter) != string::npos) {
index = str.find(delimiter);
s.push_back(str.substr(0, index));
str = str.substr(index + 1);
if (str.find(delimiter) == string::npos) {
s.push_back(str);
return;
}
}
s.push_back(str);
}
int main() {
string str = "stay hangry, stay foolish";
string s = " ";
vector<string> V;
spilt(V, str, s);
for(string v : V) {
cout << v << endl;
}
return 0;
}
使用g++运行上述代码,输出如下
stay
hangry,
stay
foolish
以上