简单来说就是使用vector容器,以字符串为分界线,分割后的字符串以string保存在vector中。
vector<string> split(string st, char sign){
vector<string> str;
for(int i = 0; i < st.length(); i++){
string temp="";
while(st[i]!=sign && i <st.length()){
temp += st[i];
i++;
}
str.push_back(temp);
}
return str;
}
完整代码
#include<iostream>
#include<vector>
#define INF 9999999
#define MAXN 1000
#include<algorithm>
using namespace std;
#include<vector>
vector<string> split(string st, char sign){
vector<string> str;
for(int i = 0; i < st.length(); i++){
string temp="";
while(st[i]!=sign && i <st.length()){
temp += st[i];
i++;
}
str.push_back(temp);
}
return str;
}
int main(){
string st;
st = " 123, 456";
vector<string> str = split(st,',');
for(int i = 0; i < str.size(); i++){
cout << str[i] <<endl;
}
return 0;
}
|