c++基础:数据类型转换及处理(二)文件路径截取文件名

版权声明:本文为博主原创文章,未经博主允许不得转载商用。 https://blog.csdn.net/andy_5826_liu/article/details/85005859

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

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

一、字符串完全替换

以下方法可以替换掉所有的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(".")) ;

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

ps: 还碰到很多在java很容易做到的问题,c++需要一堆代码处理的基础问题,慢慢整理中...
c++基础:数据类型转换及处理(一)string转wstring及文件拷贝

猜你喜欢

转载自blog.csdn.net/andy_5826_liu/article/details/85005859
今日推荐