在c++中,如何知道字符串是否以另一个字符串结束?


当前回答

使用std::equal算法从<algorithms>与反向迭代:

std::string LogExt = ".log";
if (std::equal(LogExt.rbegin(), LogExt.rend(), filename.rbegin())) {
   …
}

从c++ 20开始引入ends_with。

其他回答

如果像我一样,你需要endsWith来检查文件扩展名,你可以使用std::filesystem库:

std::filesystem::path("/foo/bar.txt").extension() == ".txt"

在我看来,最简单的c++解决方案是:

bool endsWith(const std::string& s, const std::string& suffix)
{
    return s.rfind(suffix) == std::abs(s.size()-suffix.size());
}

警告:如果匹配失败,这将在放弃之前向后搜索整个字符串,从而可能浪费大量循环。

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;
}

std::mismatch方法可以用于从两个字符串的末尾开始向后迭代:

const string sNoFruit = "ThisOneEndsOnNothingMuchFruitLike";
const string sOrange = "ThisOneEndsOnOrange";

const string sPattern = "Orange";

assert( mismatch( sPattern.rbegin(), sPattern.rend(), sNoFruit.rbegin() )
          .first != sPattern.rend() );

assert( mismatch( sPattern.rbegin(), sPattern.rend(), sOrange.rbegin() )
          .first == sPattern.rend() );
bool EndsWith(const std::string& data, const std::string& suffix)
{
    return data.find(suffix, data.size() - suffix.size()) != std::string::npos;
}

测试

#include <iostream>
int main()
{
   cout << EndsWith(u8"o!hello!1", u8"o!") << endl; 
   cout << EndsWith(u8"o!hello!", u8"o!") << endl; 
   cout << EndsWith(u8"hello!", u8"o!") << endl; 
   cout << EndsWith(u8"o!hello!o!", u8"o!") << endl; 
   return 0;
}

输出

0 
1 
1 
1