一个C++函数,用于测试 C 字符串是否以后缀结尾

A C++ function that tests if the C string ends with a suffix

本文关键字:是否 字符串 后缀 结尾 测试 C++ 函数 用于 一个      更新时间:2023-10-16
bool endsWith(const char* str, const char* suffix)
测试 C 字符串

str 是否以指定的后缀(C 字符串后缀(结尾。

例子:

endsWith("hot dog", "dog")        // Should return true
endsWith("hot dog", "cat")        // Should return false
endsWith("hot dog", "doggle")     // Should return false

我有:

bool endsWith(const char* str, const char* suffix){
if(strstr(str, suffix)==(strlen(str)-strlen(suffix)))
return true;
else
return false;
}

不使用std::string的另一种解决方案可能是:

bool strendswith(const char* str, const char* suffix)
{
    int len = strlen(str);
    int suffixlen = strlen(suffix);
    if(suffixlen > len)
    {
        return false;
    }
    str += (len - suffixlen);
    return strcmp(str, suffix) == 0;
}

你并没有真正问一个问题,但你提到了一个C++函数,所以:

bool endsWith(std::string str, std::string suffix)
{
  if (str.length() < suffix.length())
    return false;
  return str.substr(str.length() - suffix.length()) == suffix;
}