coproc
coproc

Reputation: 6247

C++ string equivalent for strrchr

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>)

Upvotes: 5

Views: 5867

Answers (4)

ecatmur
ecatmur

Reputation: 157354

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.

Upvotes: 4

Johannes S.
Johannes S.

Reputation: 4626

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();

Upvotes: 3

Vijay
Vijay

Reputation: 67221

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.

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279255

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.

Upvotes: 1

Related Questions