在c++中,如何知道字符串是否以另一个字符串结束?
当前回答
bool endswith(const std::string &str, const std::string &suffix)
{
string::size_type totalSize = str.size();
string::size_type suffixSize = suffix.size();
if(totalSize < suffixSize) {
return false;
}
return str.compare(totalSize - suffixSize, suffixSize, suffix) == 0;
}
其他回答
使用这个函数:
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
使用std::equal算法从<algorithms>与反向迭代:
std::string LogExt = ".log";
if (std::equal(LogExt.rbegin(), LogExt.rend(), filename.rbegin())) {
…
}
从c++ 20开始引入ends_with。
关于Grzegorz Bazior反应。我使用了这个实现,但原来的一个有bug(如果我比较“..”与“.so”,则返回true)。 我建议修改函数:
bool endsWith(const string& s, const string& suffix)
{
return s.size() >= suffix.size() && s.rfind(suffix) == (s.size()-suffix.size());
}
检查str是否有后缀,使用如下:
/*
Check string is end with extension/suffix
*/
int strEndWith(char* str, const char* suffix)
{
size_t strLen = strlen(str);
size_t suffixLen = strlen(suffix);
if (suffixLen <= strLen) {
return strncmp(str + strLen - suffixLen, suffix, suffixLen) == 0;
}
return 0;
}
另一种选择是使用正则表达式。下面的代码使搜索对大小写不敏感:
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
return std::regex_search(str,
std::regex(std::string(suffix) + "$", std::regex_constants::icase));
}
可能不是很有效,但是很容易实现。
推荐文章
- 转换Python程序到C/ c++代码?
- 使用goto有什么问题?
- 度量c++中函数的执行时间
- 我如何类型定义一个函数指针与c++ 11使用语法?
- cbegin/cend背后的原因是什么?
- 如何在Eclipse CDT中启用c++ 11/ c++ 0x支持?
- 将string (or char*)转换为wstring (or wchar_t*)
- 如何停止c++控制台应用程序从退出立即?
- Java的assertEquals方法可靠吗?
- 字符串作为SQL数据库的主键
- 有没有替换Windows (Visual C)的unistd.h ?
- 从列中的字符串中删除不需要的部分
- 在c#中转换字符串为类型
- 目标文件中无法解析的外部符号
- 替换c#字符串中的多个字符