获取文件名字,路劲中的某一部分信息

 1 // Note:Your choice is C++ IDE
 2 #include <iostream>
 3 #include <string>
 4 using namespace std;
 5 //获取文件名字
 6 string getFilename(string s) {
 7     char sep = '/';
 8     char sepExt='.';
 9     
10     #ifdef _WIN32
11         sep = '\';
12     #endif
13     
14 /*
15     string  中的find()函数:
16                           找到 -- 返回 第一个字符的索引
17                           没找到--返回   string::npos
18                rfind()函数,反向查找!
19     
20 (1)size_t find (const string& str, size_t pos = 0) const;  //查找对象--string类对象
21 (2)size_t find (const char* s, size_t pos = 0) const; //查找对象--字符串
22 (3)size_t find (const char* s, size_t pos, size_t n) const;  //查找对象--字符串的前n个字符
23 (4)size_t find (char c, size_t pos = 0) const;  //查找对象--字符
24 */
25     size_t i = s.rfind(sep, s.length( ));
26     if (i != string::npos) {
27         string fn= (s.substr(i+1, s.length( ) - i));//substr主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。
28         size_t j = fn.rfind(sepExt, fn.length( ));
29         if (i != string::npos) {
30             return fn.substr(0,j);
31         }else{
32             return fn;
33         }
34     }else{
35         return "";
36     }
37 }
38 
39 int main()
40 {
41     string filename = "E:\Picture\aa.jpg";
42     string filename_whithoutExt=getFilename(filename);//如果图片路径为E:\Picture\aa.jpg..那么它为aa
43                                                                         //E:\Picture那么它就是:Picture
44     cout << "working with file: "<< filename_whithoutExt << "
";
45     return 0;
46 }

获取文件名字,路劲中的某一部分信息