C++ 字符串分割逗号——史上最优雅的一个实现

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) {
    
    
        // [start, position) 为分割下来的字符串
        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);//更新start 从pose开始
        
        pose=s.find_first_of(delema1,start);//更新pos,从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;
}

猜你喜欢

转载自blog.csdn.net/qq_37581730/article/details/108975106