Here is my filepath my/example/path
I need to capture /path
and assign it to a variable. I don't know if this involves regex, what is the best way to do this in C++?
Asked
Active
Viewed 42 times
0
-
I dont think this require regex just loop through the characters and save the position of `/` each time you encounter it, so at the end you have the last one position and from there you are good to go – Eraklon Feb 22 '20 at 21:46
-
Regular expressions would be overkill here. Read about `std::basic_string::rfind`. – Pete Becker Feb 22 '20 at 21:47
-
This might help you https://stackoverflow.com/questions/10058606/splitting-a-string-by-a-character – Tarek Dakhran Feb 22 '20 at 21:59
1 Answers
-1
The fun thing is that http://www.cplusplus.com/reference/string/string/find_last_of/ has an example which almost exactly what you are looking for.
// string::find_last_of
#include <iostream> // std::cout
#include <string> // std::string
#include <cstddef> // std::size_t
void SplitFilename (const std::string& str)
{
std::cout << "Splitting: " << str << '\n';
std::size_t found = str.find_last_of("/\\");
std::cout << " path: " << str.substr(0,found) << '\n';
std::cout << " file: " << str.substr(found+1) << '\n'; // you will need `found` only
}
int main ()
{
std::string str1 ("/usr/bin/man");
std::string str2 ("c:\\windows\\winhelp.exe");
SplitFilename (str1);
SplitFilename (str2);
return 0;
}
Output
Splitting: /usr/bin/man
path: /usr/bin
file: man
Splitting: c:\windows\winhelp.exe
path: c:\windows
file: winhelp.exe

Eraklon
- 4,206
- 2
- 13
- 29