In my C++ program, I have the string
string s = "/usr/file.gz";
Here, how to make the script to check for .gz
extention (whatever the file name is) and split it like "/usr/file"
?
In my C++ program, I have the string
string s = "/usr/file.gz";
Here, how to make the script to check for .gz
extention (whatever the file name is) and split it like "/usr/file"
?
How about:
// Check if the last three characters match the ext.
const std::string ext(".gz");
if ( s != ext &&
s.size() > ext.size() &&
s.substr(s.size() - ext.size()) == ".gz" )
{
// if so then strip them off
s = s.substr(0, s.size() - ext.size());
}
s.size() > 3
, as ".gz"
is a hidden file and should not be stripped to ""
. ( * I stripped too much, added *
and then did a rm -rf /*
)
ends_with
method like in Java or Python? And what is the point of s != ext
? The code would work equally well without that comparison.
Oct 10, 2019 at 4:09
If you're able to use C++11, you can use #include <regex>
or if you're stuck with C++03 you can use Boost.Regex (or PCRE) to form a proper regular expression to break out the parts of a filename you want. Another approach is to use Boost.Filesystem for parsing paths properly.
void stripExtension(std::string &path)
{
int dot = path.rfind(".gz");
if (dot != std::string::npos)
{
path.resize(dot);
}
}
Or shorter version of another answer (C++11)
std::string stripExtension(const std::string &filePath) {
return {filePath, 0, filePath.rfind('.')};
}