原文: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()