C++的字符串分割函数

C++的字符串没有分割函数,因此需要自己写方便使用。而受到开发工具的影响,有很多用起来比较麻烦啦,下面这个比较不错奥。


用STL进行字符串的分割 


涉及到string类的两个函数find和substr:
1、find函数
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出现的位置。
参数说明:str为子字符串,pos为初始查找位置。
返回值:找到的话返回第一次出现的位置,否则返回string::npos 


2、substr函数
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:获得子字符串。
参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
返回值:子字符串 


实现如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /* 
  2.         File      : split1.cpp 
  3.         Author    : Mike 
  4.         E-Mail    : Mike_Zhang@live.com 
  5.  */  
  6. #include <iostream>  
  7. #include <string>  
  8. #include <vector>  
  9.   
  10. //字符串分割函数  
  11. std::vector<std::string> split(std::string str,std::string pattern)  
  12. {  
  13.     std::string::size_type pos;  
  14.     std::vector<std::string> result;  
  15.     str+=pattern;//扩展字符串以方便操作  
  16.     int size=str.size();  
  17.   
  18.     for(int i=0; i<size; i++)  
  19.     {  
  20.         pos=str.find(pattern,i);  
  21.         if(pos<size)  
  22.         {  
  23.             std::string s=str.substr(i,pos-i);  
  24.             result.push_back(s);  
  25.             i=pos+pattern.size()-1;  
  26.         }  
  27.     }  
  28.     return result;  
  29. }  
  30.   
  31. int main()  
  32. {  
  33.     std::string str;  
  34.     std::cout<<"Please input str:"<<std::endl;  
  35.     //std::cin>>str;  
  36.     getline(std::cin,str);  
  37.     std::string pattern;  
  38.     std::cout<<"Please input pattern:"<<std::endl;  
  39.     //std::cin>>pattern;  
  40.     getline(std::cin,pattern);//用于获取含空格的字符串  
  41.     std::vector<std::string> result=split(str,pattern);  
  42.     std::cout<<"The result:"<<std::endl;  
  43.     for(int i=0; i<result.size(); i++)  
  44.     {  
  45.         std::cout<<result[i]<<std::endl;  
  46.     }  
  47.   
  48.     std::cin.get();  
  49.     std::cin.get();  
  50.     return 0;  
  51. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值