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

itlao6 原创 开发&源码 C++评论656字数 957阅读3分11秒阅读模式

继续昨天未写完的...我是初学者,如果觉得太简单,勿喷,如果有什么错误之处,请指出,多谢~!

今天整理了写的根据文件路径截取文件名相关代码,主要包含替换路径中的“/”为“'\”,然后根据“\”截取最后的字符串,即文件名文章源自IT老刘-https://itlao6.com/708.html

一、字符串完全替换

以下方法可以替换掉所有的src,替换为dst文章源自IT老刘-https://itlao6.com/708.html

/**
 * 字符串替换 将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;
    }
}

获取文件名

以下是获取文件名文章源自IT老刘-https://itlao6.com/708.html

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

但是有时候,我们不需要文件后缀,于是就有了以下代码:文章源自IT老刘-https://itlao6.com/708.html

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

当然,中间的两个位置自行先判断大小,我这只是截取最后一个“\”到最后一个“.”中间的字符串,并未考虑异常情况。
原文:简书ThinkinLiu 博客: IT老五文章源自IT老刘-https://itlao6.com/708.html

ps: 还碰到很多在java很容易做到的问题,c++需要一堆代码处理的基础问题,慢慢整理中...
c++基础(一):string转wstring及文件拷贝文章源自IT老刘-https://itlao6.com/708.html

作者:ThinkinLiu
链接:https://www.jianshu.com/p/1486b8a9ea0c
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。文章源自IT老刘-https://itlao6.com/708.html

文章源自IT老刘-https://itlao6.com/708.html文章源自IT老刘-https://itlao6.com/708.html
继续阅读
weinxin
我的微信公众号
微信扫一扫关注公众号,不定时更新
itlao6
  • 本文由 发表于 2018年 12月 14日 12:58:06
  • 转载请务必保留本文链接:https://itlao6.com/708.html
评论  0  访客  0
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定