C++:从完整路径中提取文件名、不带后缀的名字、后缀名(转)

原文:https://blog.csdn.net/jumencibaliang92/article/details/99051140

目的:从完整路径中提取文件名、不带后缀的名字、后缀名

如下:

#include <iostream>  
#include <string> 
using namespace std;
void main()
{
	string path = "C:\\Users\\Administrator\\Desktop\\text\\data.22.txt";
	
	//1.获取不带路径的文件名
	string::size_type iPos = path.find_last_of('\\') + 1;
	string filename = path.substr(iPos, path.length() - iPos);
	cout << filename << endl;
 
	//2.获取不带后缀的文件名
	string name = filename.substr(0, filename.rfind("."));
	cout << name << endl;
 
	//3.获取后缀名
	string suffix_str = filename.substr(filename.find_last_of('.') + 1);
	cout << suffix_str << endl;
}

【注】:完整路径以“\\”分隔;

要点:

1. s.substr(0,5):获得字符串s中从第0位开始,长度为5的字符串;默认时的长度为从开始位置到尾。

2. find_first_of(): 在字符串中查找第一个出现的字符c;

    int find_first_of(char c, int start = 0)
    查找字符串中第1个出现的c,由位置start开始。
    如果有匹配,则返回匹配位置;否则,返回-1.

    默认情况下,start为0,函数搜索整个字符串。

3. find_last_of():在字符串中查找最后一个出现的字符c;
    int find_last_of(char c):
    查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1.
    该搜索在字符末尾查找匹配,所以没有提供起始位置。

4. find()正向查找,rfind()反向查找

(1)size_t find (const string& str, size_t pos = 0) const;  //查找对象-string类对象

(2)size_t find (const char* s, size_t pos = 0) const; //查找对象-字符串

(3)size_t find (const char* s, size_t pos, size_t n) const;  //查找对象-字符串的前n个字符

(4)size_t find (char c, size_t pos = 0) const;  //查找对象--字符

    结果:找到, 返回 第一个字符的索引; 没找到--返回   string::npos

参考文章:

1. https://blog.csdn.net/zhangla1220/article/details/39028269

2. https://blog.csdn.net/shaoyiju/article/details/78377132  根据文件路径获取文件名

3. https://blog.csdn.net/no_retreats/article/details/7853066 substr的用法

4. https://blog.csdn.net/fengyeer20120/article/details/79741491

5. https://blog.csdn.net/wanglei5695312/article/details/4998062  find_first_of()和 find_last_of()

6. https://www.cnblogs.com/cynthia-dcg/p/6178650.html  find()和rfind()

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值