C++11以前有很多原因不能提供一个通用的split,比如说需要考虑split以后的结果存储在什么类型
的容器中,可以是vector、list等等包括自定义容器,很难提供一个通用的;再比如说需要split的源
字符串很大的时候运算的时间可能会很长,所以这个split最好是lazy的,每次只返回一条结果。
C++11之前只能自己写,我目前发现的史上最优雅的一个实现是这样的:
void split(const std::string& str,
std::vector<std::string>& tokens,
const std::string delim = " ") {
tokens.clear();
auto start = str.find_first_not_of(delim, 0);
auto position = str.find_first_of(delim, start);
while (position != std::string::npos || start != std::string::npos) {
tokens.emplace_back(std::move(str.substr(start, position - start)));
start = str.find_first_not_of(delim, position);
position = str.find_first_of(delim, start);
}
}
实现
void split(string& s,vector<string>&res,string& delema1){
string::size_type start=s.find_first_not_of(delema1,0);
string::size_type pose=s.find_first_of(delema1,start);
while(string::npos!=start||string::npos!=pose){
res.push_back(s.substr(start,pose-start));
start=s.find_first_not_of(delema1,pose);
pose=s.find_first_of(delema1,start);
}
}
int main(){
string s=",1,2,3,45,,67";
vector<string> Res;
string Delema=",";
split(s,Res,Delema);
for(auto& i:Res)
cout<<i<<endl;
return 0;
}