一个C++函数,用于测试 C 字符串是否以后缀结尾
A C++ function that tests if the C string ends with a suffix
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;
}
相关文章:
- 是否可以在c++中处理字符串流中的各个元素
- 是否可以从格式字符串中检索"width"
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 是否可以将带有字符串化运算符的宏转换为 constexpr?
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 是否有通用方法可以找到任何以 null 结尾的字符串的长度?
- 检查字符串是否为整数
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 返回从字符串文本创建的静态string_view是否安全?
- 如何检查模板类中的变量是否为字符串类型?
- 是否保证相同内容字符串文本的存储相同?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 是否可以创建一个用户定义的文本,将字符串文本转换为 own 类型的数组?
- 如何检查字符串中是否有重复的负号?例如 --1
- 如何检查字符串是否正确以将其转换为 int?