使用 C 字符串,我将编写以下代码来从文件路径获取文件名:
#include <string.h>
const char* filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
const char* fileName = strrchr(progPath, '\\');
if (fileName)
++fileName;
else
fileName = filePath;
Run Code Online (Sandbox Code Playgroud)
如何对 C++ 字符串执行同样的操作?(即使用std::stringfrom #include <string>)
最接近的等价物是rfind:
#include <string>
std::string filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
std::string::size_type filePos = filePath.rfind('\\');
if (filePos != std::string::npos)
++filePos;
else
filePos = 0;
std::string fileName = filePath.substr(filePos);
Run Code Online (Sandbox Code Playgroud)
请注意,rfind返回字符串的索引(或npos),而不是指针。
| 归档时间: |
|
| 查看次数: |
5530 次 |
| 最近记录: |