在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());
  }