在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
推荐文章
- 转换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#字符串中的多个字符