C++分割字符串

来源:互联网 发布:广西航信金税盘软件 编辑:程序博客网 时间:2024/06/06 14:15
#include <iostream>#include <string>#include <vector>//字符串分割函数std::vector<std::string> split(std::string str,std::string pattern){  std::string::size_type pos;  std::vector<std::string> result;  str+=pattern;            //扩展字符串以方便操作  int size=str.size();      //str.size() 表示str中有几个元素  for(int i=0; i<size; i++)  {    pos=str.find(pattern,i);   //str.find(pattern,i)表示从i位置开始找pattern,如果找到,则返回位置,否则返回string::npos    if(pos < size)    {      std::string s=str.substr(i,pos-i); //str.substr(i,pos-i)表示从i位置开始切割,切割长度为pos-i长      result.push_back(s);      //将结果push出去      i=pos+pattern.size()-1;   //长度变化,再继续找下一个pattern    }  }  return result;}int main(){  std::string str,pattern;    //设string类型的str和pattern  str="sss/ddd/ggg/hh";  pattern="/";  std::vector<std::string> result=split(str,pattern);    //std::vector<std::string> 可以看做string的指针或者数组  std::cout<<"The result:"<<std::endl;  for(int i=0; i<result.size(); i++)  {    std::cout<<result[i]<<std::endl;      //将分割的结果输出  }  std::cin.get();     //获取最后一个字符并保存,结束进程  std::cin.get();     //如果这两句话放在程序中间,则后面部分的程序不会再运行  return 0;}

结果显示如下