C++ string equivalent for strrchr

2019-01-28 07:26发布

问题:

Using C strings I would write the following code to get the file name from a file path:

#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;

How to do the same with C++ strings? (i.e. using std::string from #include <string>)

回答1:

The closest equivalent is 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);

Note that rfind returns an index into the string (or npos), not a pointer.



回答2:

To find the last occurence of a symbol in a string use std::string::rfind

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

However, if you're handling filenames and pathes more often, have a look at boost::filesystem

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


回答3:

Either call string::rfind(), or call std::find using reverse iterators (which are returned from string::rbegin() and string::rend()).

find might be a little bit more efficient since it explicitly says that you're looking for a matching character. rfind() looks for a substring and you'd give it a length 1 string, so it finds the same thing.



回答4:

Apart from rfind(), you can also use find_last_of() You have an example too written in cplusplus.com which is same as your requirement.



标签: c++ std