目的:从完整路径中提取文件名、不带后缀的名字、后缀名
如下:
#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;
}
【注】:完整路径以“\”分隔;
要点:
- s.substr(0,5):获得字符串s中从第0位开始,长度为5的字符串;默认时的长度为从开始位置到尾。
- find_first_of(): 在字符串中查找第一个出现的字符c;
int find_first_of(char c, int start = 0)
查找字符串中第1个出现的c,由位置start开始。
如果有匹配,则返回匹配位置;否则,返回-1.
默认情况下,start为0,函数搜索整个字符串。 - find_last_of():在字符串中查找最后一个出现的字符c;
int find_last_of(char c):
查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1.
该搜索在字符末尾查找匹配,所以没有提供起始位置。 - 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
参考文章:
- https://blog.csdn.net/zhangla1220/article/details/39028269
- https://blog.csdn.net/shaoyiju/article/details/78377132 根据文件路径获取文件名
- https://blog.csdn.net/no_retreats/article/details/7853066 substr的用法
- https://blog.csdn.net/fengyeer20120/article/details/79741491
- https://blog.csdn.net/wanglei5695312/article/details/4998062 find_first_of()和 find_last_of()
- https://www.cnblogs.com/cynthia-dcg/p/6178650.html find()和rfind()
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询