其他分享
首页 > 其他分享> > string根据特殊字符分割字符串

string根据特殊字符分割字符串

作者:互联网

std::string test_str = "year,mon,day,hh";
  std::vector<std::string> res = splitwithstr(test_str, ',');
  for (int i=0; i<res.size(); i++)
  {
    std::cout << res[i] << std::endl;
  }


std::vector<std::string> splitwithstr(std::string &str,char ch)
{
  std::string tmpstr = str+ch;
  std::vector<std::string> res;
  if (str.size()<=0)
  {
    return res;
  }

  size_t pos = tmpstr.find(ch);
  size_t size = tmpstr.size();
  while (pos!=std::string::npos)
  {
    std::string child_str = tmpstr.substr(0, pos);
    if (child_str.size()>0)
    {
      res.push_back(child_str);
    }
    tmpstr = tmpstr.substr(pos + 1);
    pos = tmpstr.find(ch);
  }
  return res;
}


int main() {
    char s[] = "my name is lmm";
    char *p;
    const char *delim = " ";
    p = strtok(s, delim);
    while(p) {
        cout << p << endl;
        p = strtok(NULL, delim);
    }
 
    return 0;
}

 

标签:std,string,res,char,str,字符串,tmpstr,特殊字符
来源: https://www.cnblogs.com/LuckCoder/p/11715592.html