1.函数作用
从一个完整的文件路径中提取出文件名,去除文件路径和文件扩展名。

2.函数代码
string getFileName(const std::string& filePath){
size_t lastSlash = filePath.find_last_of("/\\");
size_t lastDot = filePath.find_last_of(".");
if(lastDot == std::string::npos){
lastDot = filePath.length();
}
return filePath.substr(lastSlash+1, lastDot-lastSlash - 1);
}
3.函数详细说明
- find_last_of函数用于查找字符串中最后出现的字符位置;
- lastSlash找到最后一个路径分割符的索引,找不到表示没有路径分割符;
- lastDot找用于分隔文件名和扩展名的”.“。
- substr(lastSlash+1, lastDot-lastSlash - 1);
- 提取字符串中的子字符串;
- lastSlash+1表示子字符串从最后一个路径分隔符后开始;
- lastDot-lastSlash - 1表示子字符串的长度,表示从第一个字符开始,到扩展名之前的最后一个字符结束。
270

被折叠的 条评论
为什么被折叠?



