bool endsWith(const char* str, const char* suffix)
Tests if the C string str ends with the specified suffix, the C string suffix.
Examples:
endsWith("hot dog", "dog") // Should return true
endsWith("hot dog", "cat") // Should return false
endsWith("hot dog", "doggle") // Should return false
I have:
bool endsWith(const char* str, const char* suffix){
if(strstr(str, suffix)==(strlen(str)-strlen(suffix)))
return true;
else
return false;
}
Another solution not using std::string
could be this:
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;
}
You didn't really ask a question, but you mentioned a C++ function, so:
bool endsWith(std::string str, std::string suffix)
{
if (str.length() < suffix.length())
return false;
return str.substr(str.length() - suffix.length()) == suffix;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.