在c++中,如何知道字符串是否以另一个字符串结束?
当前回答
找到了类似的"startWith"问题的好答案:
如何检查一个c++ std::string是否以某个字符串开始,并将子字符串转换为int?
你可以采用只搜索字符串的最后一个位置的解决方案:
bool endsWith(const std::string& stack, const std::string& needle) {
return stack.find(needle, stack.size() - needle.size()) != std::string::npos;
}
这样你可以使它短小、快速、使用标准c++并使其可读。
其他回答
另一种选择是使用正则表达式。下面的代码使搜索对大小写不敏感:
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
return std::regex_search(str,
std::regex(std::string(suffix) + "$", std::regex_constants::icase));
}
可能不是很有效,但是很容易实现。
设a是一个字符串,b是你要找的字符串。使用a.s ustr获取a的最后n个字符,并将它们与b进行比较(其中n是b的长度)
或者使用std::equal (include <algorithm>)
Ex:
bool EndsWith(const string& a, const string& b) {
if (b.size() > a.size()) return false;
return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin());
}
让我用不区分大小写的版本扩展Joseph的解决方案(在线演示)
#include <string>
#include <cctype>
static bool EndsWithCaseInsensitive(const std::string& value, const std::string& ending) {
if (ending.size() > value.size()) {
return false;
}
return std::equal(ending.crbegin(), ending.crend(), value.crbegin(),
[](const unsigned char a, const unsigned char b) {
return std::tolower(a) == std::tolower(b);
}
);
}
在我看来,最简单的c++解决方案是:
bool endsWith(const std::string& s, const std::string& suffix)
{
return s.rfind(suffix) == std::abs(s.size()-suffix.size());
}
警告:如果匹配失败,这将在放弃之前向后搜索整个字符串,从而可能浪费大量循环。
和上面一样,这是我的解
template<typename TString>
inline bool starts_with(const TString& str, const TString& start) {
if (start.size() > str.size()) return false;
return str.compare(0, start.size(), start) == 0;
}
template<typename TString>
inline bool ends_with(const TString& str, const TString& end) {
if (end.size() > str.size()) return false;
return std::equal(end.rbegin(), end.rend(), str.rbegin());
}
推荐文章
- 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#字符串中的多个字符
- Java中字符串的字节数
- Lambda捕获作为const引用?
- 如何从c风格数组初始化std::vector ?
- 是std::vector复制对象push_back?