写了个稍微简单通用的,快让字符串搞疯了!
对于:
string s1=" aaa bbb ccc ddd ";
string s2=", ,aaa,bbb ,ccc ,,,ddd,, ";
这种乱糟糟的都可以用。
void stringSplit(string s,string delim,vector<string> &ans)
{
string::size_type pos_1,pos_2=0;
while(pos_2!=s.npos){
pos_1=s.find_first_not_of(delim,pos_2);
if(pos_1==s.npos) break;
pos_2=s.find_first_of(delim,pos_1);
ans.push_back(s.substr(pos_1,pos_2-pos_1));
}
}
这还有个按长度分割的:
void stringSplit(string s,int sub_len,vector<string> &ans)
{
string::size_type pos=0;
while(pos<s.length()){
if(pos+sub_len>s.length()) ans.push_back(s.substr(pos));
else ans.push_back(s.substr(pos,sub_len));
pos+=sub_len;
}
}