2025年3月29日 星期六 甲辰(龙)年 月廿八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

c++基础(二):字符串替换及文件路径截取文件名

时间:03-01来源:作者:点击数:48

今天整理了写的根据文件路径截取文件名相关代码,主要包含替换路径中的“/”为“'\”,然后根据“\”截取最后的字符串,即文件名

一、字符串完全替换

以下方法可以替换掉所有的src,替换为dst

  • /**
  • * 字符串替换 将str中所有的src替换为dst
  • */
  • void SlpcalHelper::string_replaceAll(std::string &str, const std::string &src, const std::string &dst)
  • {
  • std::string::size_type pos = 0;
  • std::string::size_type srclen = src.size();
  • std::string::size_type dstlen = dst.size();
  • while ((pos = str.find(src, pos)) != std::string::npos)
  • {
  • str.replace(pos, srclen, dst);
  • pos += dstlen;
  • }
  • }

获取文件名

以下是获取文件名

  • // 先替换字符串
  • string_replaceAll(strPath, "/", "\\");
  • // 获取文件名
  • std::string tempFileName = strPath.substr(strPath.find_last_of("\\") + 1);

但是有时候,我们不需要文件后缀,于是就有了以下代码:

  • std::string fileName= strPath.substr(strPath.find_last_of("\\") + 1, strPath.find_last_of(".")) ;

当然,中间的两个位置自行先判断大小,我这只是截取最后一个“\”到最后一个“.”中间的字符串,并未考虑异常情况。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门