I have 2 strings like this:
In these 2 cases I want to get "File1.txt" and "File2.txt" and put them to a string.
I need the same method so I suppose I have to find the Last "/" in the string and then
put the rest to a new string.

What method and approach can be used to do this ?

std::string Line1 = "c:\Folder1\File1.txt";
std::string Line2 = "c:\Folder1\Folder2\File2.txt";

Dani AI

Generated

correctly suggested searching for the last separator and 's rfind+substr approach is a perfectly fine quick fix (and solved 's case). For more robust, maintainable code, prefer a path-aware API when available and watch a few common pitfalls.

A modern, portable solution (C++17+) is std::filesystem::path::filename — it returns the final component without manually parsing separators:

#include <filesystem>
#include <string>

std::filesystem::path p(R"(c:\Folder1\Folder2\File2.txt)");
std::string filename = p.filename().string(); // "File2.txt"

Compile with C++17 support. See the std::filesystem::path::filename reference for details: std::filesystem::path::filename.

If you cannot use C++17, implement the same logic carefully: find the last occurrence of either '/' or '\' and take the characters after it; if none is found, the whole string is the name. Important caveats: escape backslashes in C++ string literals (or use raw string literals) to avoid accidental escape sequences, handle inputs that end with a separator, and treat empty or root-only paths explicitly.

Edge cases to test: paths with trailing separators, UNC paths, relative names like "." or "..", and non-ASCII filenames on Windows (consider using wide strings and the path wstring APIs when interacting with native Windows APIs). Using std::filesystem avoids many of these traps and is the recommended approach for production code.

Recommended Answers

All 4 Replies

If you need to "find the Last "/" in the string" try using the std::string::find_last_of() to get index of the last slash in a string. For details see e.g. here

There are many ways but here's one:

string filename = Line1.substr(Line1.rfind("\\")+1, string::npos);

I didn't test this BTW.

EDITED: Added the extra \

That could even be:

string filename = Line1.substr(Line1.rfind("\\")+1);

to make it a bit shorter.

Thanks again codeaa. That solved the problem nicely !

EDITED: Added the extra \

That could even be:

string filename = Line1.substr(Line1.rfind("\\")+1);

to make it a bit shorter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.