在c++中,如何知道字符串是否以另一个字符串结束?
当前回答
我知道这个问题是针对c++的,但如果有人需要一个很好的老式C函数来做到这一点:
/* returns 1 iff str ends with suffix */
int str_ends_with(const char * str, const char * suffix) {
if( str == NULL || suffix == NULL )
return 0;
size_t str_len = strlen(str);
size_t suffix_len = strlen(suffix);
if(suffix_len > str_len)
return 0;
return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len );
}
其他回答
如果像我一样,你需要endsWith来检查文件扩展名,你可以使用std::filesystem库:
std::filesystem::path("/foo/bar.txt").extension() == ".txt"
我知道这个问题是针对c++的,但如果有人需要一个很好的老式C函数来做到这一点:
/* returns 1 iff str ends with suffix */
int str_ends_with(const char * str, const char * suffix) {
if( str == NULL || suffix == NULL )
return 0;
size_t str_len = strlen(str);
size_t suffix_len = strlen(suffix);
if(suffix_len > str_len)
return 0;
return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len );
}
我认为发布一个不使用任何库函数的原始解决方案是有意义的…
// Checks whether `str' ends with `suffix'
bool endsWith(const std::string& str, const std::string& suffix) {
if (&suffix == &str) return true; // str and suffix are the same string
if (suffix.length() > str.length()) return false;
size_t delta = str.length() - suffix.length();
for (size_t i = 0; i < suffix.length(); ++i) {
if (suffix[i] != str[delta + i]) return false;
}
return true;
}
添加一个简单的std::tolower,我们可以使这种情况不敏感
// Checks whether `str' ends with `suffix' ignoring case
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
if (&suffix == &str) return true; // str and suffix are the same string
if (suffix.length() > str.length()) return false;
size_t delta = str.length() - suffix.length();
for (size_t i = 0; i < suffix.length(); ++i) {
if (std::tolower(suffix[i]) != std::tolower(str[delta + i])) return false;
}
return true;
}
使用这个函数:
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());
}
在我看来,最简单的c++解决方案是:
bool endsWith(const std::string& s, const std::string& suffix)
{
return s.rfind(suffix) == std::abs(s.size()-suffix.size());
}
警告:如果匹配失败,这将在放弃之前向后搜索整个字符串,从而可能浪费大量循环。
推荐文章
- 转换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#字符串中的多个字符