記錄一種操作字符串獲取文件名字的操作方式,方便后期的使用。示例:
輸入:"D:/code/Test/Test.txt"
輸出:"Test.txt"
設計思路:
? ? ? ? 首先查找路徑中最后一個”/“,然后再通過字符串截取的方式,獲取文件名。
?代碼具體實現:
#include<string>
#include <ctype.h>
#define ISPATHPART(c) ((c)=='/'||(c)=='\\')std::string GetName(const std::string& strPathFile)
{if (!strPathFile.empty()){int number = 0, index = 0;if (isalpha(strPathFile[0]) && strPathFile[1] == ':'){index = 1;number = index + 1;}index++;int nlen = strPathFile.length();while (index<nlen){if (ISPATHPART(strPathFile[index])){number = index + 1;}index++;}return std::string(strPathFile.c_str()+ number, nlen-number);}return"";
}int main()
{std::string path = "D:/code/Test/Test.txt";path = GetName(path);return 0;
}
測試結果: