c++ check that const char* has suffix
To check if a const char*
has a specific suffix in C++, you can use the std::string
class from the <string>
header. Here are the steps to do that:
Convert the
const char*
to anstd::string
:cpp const char* str = "example.txt"; std::string s(str);
Use the
substr
function to extract the suffix from thestd::string
:cpp std::string suffix = s.substr(s.length() - suffix.length());
In this step, suffix
is a new std::string
that contains the last suffix.length()
characters of the original string s
.
- Compare the extracted suffix with the desired suffix:
cpp std::string desiredSuffix = ".txt"; if (suffix == desiredSuffix) { // The `const char*` has the desired suffix } else { // The `const char*` does not have the desired suffix }
In this step, you can use the ==
operator to compare the suffix
with the desired suffix. If they are equal, it means that the const char*
has the desired suffix.
Here's the complete code:
#include <string>
bool hasSuffix(const char str, const char suffix) {
std::string s(str);
std::string desiredSuffix(suffix);
std::string extractedSuffix = s.substr(s.length() - desiredSuffix.length());
return extractedSuffix == desiredSuffix;
}
You can use the hasSuffix
function to check if a const char*
has a specific suffix. For example:
const char* str = "example.txt";
const char* suffix = ".txt";
if (hasSuffix(str, suffix)) {
// The `const char*` has the desired suffix
} else {
// The `const char*` does not have the desired suffix
}