打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++ 笔试基础之 08 字符串分割函数

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)
返回值:子字符串 


实现如下

  1. #include <iostream>  
  2. #include <string>  
  3. #include <vector>  

  4. using namespace std;

  5. //字符串分割函数  
  6. vector<string> split(string str, string pattern)
  7. {
  8. string::size_type pos;
  9. vector<string> result;
  10. str += pattern;//扩展字符串以方便操作  
  11. int size = str.size();//字符串长度

  12. for (int i = 0; i<size; i++)
  13. {
  14. //pattern是子字符串,i为初始查找位置
  15. pos = str.find(pattern, i);//找到pattern在str中的位置
  16. if (pos<size)
  17. {
  18. //获取从i到pos-i的子字符串
  19. string s = str.substr(i, pos - i);
  20. result.push_back(s);//添加
  21. //下一个开始查找位置
  22. i = pos + pattern.size() - 1;
  23. }
  24. }
  25. return result;
  26. }

  27. int main()
  28. {
  29. string str="I love China is not a";
  30. string pattern = " ";
  31. vector<string> result = split(str, pattern);

  32. cout << "The result:" << endl;

  33. for (int i = 0; i<result.size(); i++)
  34. {
  35. cout << result[i] << endl;
  36. }


  37. system("pause");
  38. return 0;
  39. }

 
 


希望对您有用,上面代码来自:http://www.cnblogs.com/MikeZhang/archive/2012/03/24/mysplitfuncpp.html


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C++ string类
详细解说STL string -- STLDetailString
STL[12]string使用总结
转: std::string用法详解
C++ replace() 函数用法详解
解析字符串
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服