经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
详解C++ string常用截取字符串方法
来源:jb51  时间:2019/5/15 9:56:41  对本文有异议

string常用截取字符串方法有很多,但是配合使用以下两种,基本都能满足要求:

find(string strSub, npos);

find_last_of(string strSub, npos);

其中strSub是需要寻找的子字符串,npos为查找起始位置。找到返回子字符串首次出现的位置,否则返回-1;

注:

(1)find_last_of的npos为从末尾开始寻找的位置。

(2)下文中用到的strsub(npos,size)函数,其中npos为开始位置,size为截取大小

例1:直接查找字符串中是否具有某个字符串(返回"2")

  1. std::string strPath = "E:\\数据\\2018\\2000坐标系\\a.shp"
  2. int a = 0;
  3. if (strPath.find("2018") == std::string::npos)
  4. {
  5. a = 1;
  6. }
  7. else
  8. {
  9. a = 2;
  10. }
  11. return a;

例2:查找某个字符串的字符串(返回“E:”)

  1. std::string strPath = "E:\\数据\\2018\\2000坐标系\\a.shp"
  2. int nPos = strPath.find("\\");
  3. if(nPos != -1)
  4. {
  5. strPath = strPath.substr(0, nPos);
  6. }
  7. return strPath;

例3:查找某个字符串中某两个子字符串之间的字符串(返回“2000坐标系”)

  1. std::string strPath = "E:\\数据\\2018\\2000坐标系\\a.shp"
  2. std::string::size_type nPos1 = std::string::npos;
  3. std::string::size_type nPos2 = std::string::npos;
  4. nPos1 = strPath.find_last_of("\\");
  5. nPos2 = strPath.find_last_of("\\", nPos1 - 1);
  6. if(nPos1 !=-1 && npos2 != -1)
  7. {
  8. strPath = strPath.substr(nPos2 + 1, nPos1 - nPos2 - 1);
  9. }
  10. return strPath;

提高:递归获取路径名中的子目录

  1. //获取路径名中的子目录:strPath为路径名,strSubPath为输出的子目录,
  2. nSearch为从尾向前检索的级别(默认为1级)
  3. bool _GetSubPath(std::string& strPath,std::string& strSubPath, int nSearch)
  4. {
  5. if (-1 == nSearch || strPath.empty())
  6. return false;
  7. std::string::size_type nPos1 = std::string::npos;
  8. nPos1 = strPath.find_last_of("\\");
  9. if (nPos1 != -1)
  10. {
  11. strSubPath = strPath.substr(nPos1 + 1, strPath.length() - nPos1);
  12. int nNewSearch = nSearch > 1 ? nSearch - 1 : -1;
  13. _GetSubPath(strPath.substr(0, nPos1), strSubPath, nNewSearch);
  14. }
  15. return true;
  16. }
  17. int main()
  18. {
  19. std::string strPath = "E:\\数据\\2018\\2000坐标系\\a.shp";
  20. std::string strSubPath = "";
  21. if(_GetSubPath(strPath, strSubPath, 1)
  22. {
  23. printf(“返回'a.shp'”);
  24. }
  25. if(_GetSubPath(strPath, strSubPath, 2)
  26. {
  27. printf(“返回'2000坐标系'”);
  28. }
  29. }

以上所述是小编给大家介绍的C++ string常用截取字符串方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号