std::string::find_last_of 獲取文件名
// string::find_last_of
#include <iostream> // std::cout
#include <string> // std::string
#include <cstddef> // std::size_t
void SplitFilename (const std::string& str)
{
std::cout << "Splitting: " << str << '\n';
std::size_t found = str.find_last_of("/\\");
std::cout << " path: " << str.substr(0,found) << '\n';
std::cout << " file: " << str.substr(found+1) << '\n';
}
int main ()
{
std::string str1 ("/usr/bin/man");
std::string str2 ("c:\\windows\\winhelp.exe");
SplitFilename (str1);
SplitFilename (str2);
return 0;
}
Edit & Run
Splitting: /usr/bin/man
path: /usr/bin
file: man
Splitting: c:\windows\winhelp.exe
path: c:\windows
file: winhelp.exe
上面代碼的地址:http://www.cplusplus.com/reference/string/string/find_last_of/
上面用到的主要是std::string中find_last_of方法,我開始對這個str.find_last_of("/\")有疑問,看到一篇解釋后才明白:
** find_first_of 是給定一個要查找的字符集,找到這個字符集中任何一個字符所在字符串中第一個位置** 。或許看一個例子更容易明白。
有這樣一個需求:過濾一行開頭和結尾的所有非英文字符。看看用string 如何實現:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string strinfo=" //*---Hello Word!......------";
string strset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int first = strinfo.find_first_of(strset);
if(first == string::npos)
{
cout<<"not find any characters"<<endl;
return -1;
}
int last = strinfo.find_last_of(strset);
if(last == string::npos)
{
cout<<"not find any characters"<<endl;
return -1;
}
cout << strinfo.substr(first, last - first + 1)<<endl;
return 0;
}
這里把所有的英文字母大小寫作為了需要查找的字符集,先查找第一個英文字母的位置,然后查找最后一個英文字母的位置,然后用substr 來的到中間的一部分,用於輸出結果。下面就是其結果:
Hello Word
上面這個解釋的原文地址:
https://www.byvoid.com/blog/cpp-string
