Home > Software engineering >  Elegant way to parse a substring from string in c version 11 and up
Elegant way to parse a substring from string in c version 11 and up

Time:12-16

need to parse substring from a string for example user input : "firstdir/seconddir/myfile.txt"

need to extract "myfile.txt"

please consider that user input can be "fdsf dsf/dsfsdf/sdf dsfetresr/myfile.txt" , "myfile.txt" , "frfefrf.rewrewr/myfile.txt"

Also is regex can be use in the case regex("\w .\w ")?

CodePudding user response:

No need for regex, you can just find the last / and return a substring:

string parse(std::string s)
{
  std::size_t res = s.rfind("/");
  return res != std::string::npos ? s.substr(  res) : s;
}

If you want a regex, however, this would suffice

 [^\/] $

CodePudding user response:

string input = ...; // ie "firstdir/seconddir/myfile.txt"
auto pos = input.rfind('/');
if (pos != string::npos) input.erase(0, pos 1);
// use input as needed...

CodePudding user response:

Looks like if you want to get a filename from a path.

This seems very simple, but is not. The reason is, that filenames nowadays can contain all kind of special characters. There may be spaces in it and also multiple dotes ('.') . Depending on the file system there maybe slashes '/' (as in Unix/Linux) or backslashes '' (as in Windows systems) as separators. There are also filenames without extensions and special files starting with a period. (like ".profile"). So basically not so easy.

But C will help you. The C 17 build in filesystem library has a type path, which has a function filename

Please read here, here and here.

With that you can extract a filename in a very compatible way.

std::string filePath{"firstdir/seconddir/myfile.txt"};
std::string filename = std::filesystem::path(filePath).filename().string();

Maybe you can give it a try . . .

  • Related