在c++中,如何知道字符串是否以另一个字符串结束?
当前回答
和上面一样,这是我的解
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());
}
其他回答
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() );
你可以使用string::rfind
基于注释的完整示例:
bool EndsWith(string &str, string& key)
{
size_t keylen = key.length();
size_t strlen = str.length();
if(keylen =< strlen)
return string::npos != str.rfind(key,strlen - keylen, keylen);
else return false;
}
我的观点是:
bool endsWith(std::string str, std::string suffix)
{
return str.find(suffix, str.size() - suffix.size()) != string::npos;
}
使用boost::algorithm::ends_with(参见http://www.boost.org/doc/libs/1_34_0/doc/html/boost/algorithm/ends_with.html):
#include <boost/algorithm/string/predicate.hpp>
// works with const char*
assert(boost::algorithm::ends_with("mystring", "ing"));
// also works with std::string
std::string haystack("mystring");
std::string needle("ing");
assert(boost::algorithm::ends_with(haystack, needle));
std::string haystack2("ng");
assert(! boost::algorithm::ends_with(haystack2, needle));
找到了类似的"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++并使其可读。
推荐文章
- 度量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#字符串中的多个字符
- Java中字符串的字节数
- Lambda捕获作为const引用?