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:

  1. Convert the const char* to an std::string: cpp const char* str = "example.txt"; std::string s(str);

  2. Use the substr function to extract the suffix from the std::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.

  1. 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
}