c 字符串等效于strrchr

C++ string equivalent for strrchr

本文关键字:strrchr 字符串      更新时间:2023-10-16

使用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;

如何使用C 字符串进行相同的操作?(即使用#include <string>std::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);

请注意,rfind将索引返回到字符串(或npos),而不是指针。

在字符串中查找符号的最后一个情况使用std::string::rfind

std::string filename = "dir1\dir2\filename"; 
std::size_t pos = filename.rfind( "\" );

但是,如果您经常处理文件名和路径,请查看boost::filesystem

boost::filesystem::path p("dir1\dir2\filename");
std::string filename = p.filename().generic_string(); //or maybe p.filename().native();

呼叫string::rfind(),或使用反向迭代器调用std::find(从string::rbegin()string::rend()返回)。

find可能会更有效一些,因为它明确地说您正在寻找匹配的角色。rfind()寻找一个子字符串,您会给它一个长度1字符串,因此找到同一件事。

除了rfind(),您也可以使用find_last_of()您有一个在cplusplus.com上写的示例,该示例与您的要求相同。