找出字符串是否以 C++ 中的另一个字符串结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/874134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find out if string ends with another string in C++
提问by sofr
How can I find out if a string ends with another string in C++?
如何在 C++ 中找出一个字符串是否以另一个字符串结尾?
回答by kdt
Simply compare the last ncharacters using std::string::compare
:
只需使用以下方法比较最后n 个字符std::string::compare
:
#include <iostream>
bool hasEnding (std::string const &fullString, std::string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
int main () {
std::string test1 = "binary";
std::string test2 = "unary";
std::string test3 = "tertiary";
std::string test4 = "ry";
std::string ending = "nary";
std::cout << hasEnding (test1, ending) << std::endl;
std::cout << hasEnding (test2, ending) << std::endl;
std::cout << hasEnding (test3, ending) << std::endl;
std::cout << hasEnding (test4, ending) << std::endl;
return 0;
}
回答by Joseph
Use this function:
使用这个功能:
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
回答by Andre Holzner
Use boost::algorithm::ends_with
(see e.g. http://www.boost.org/doc/libs/1_34_0/doc/html/boost/algorithm/ends_with.html):
使用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));
回答by Pavel P
Note, that starting from c++20std::string will finally provide starts_withand ends_with. Seems like there is a chance that by c++30 strings in c++ might finally become usable, if you aren't reading this from distant future, you can use these startsWith/endsWith:
请注意,从c++20std::string开始,最终将提供starts_with和ends_with。似乎 c++ 中的 c++30 字符串有可能最终变得可用,如果你不是从遥远的未来读到这个,你可以使用这些 startsWith/endsWith:
#include <string>
static bool endsWith(const std::string& str, const std::string& suffix)
{
return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix);
}
static bool startsWith(const std::string& str, const std::string& prefix)
{
return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
}
and some extra helper overloads:
以及一些额外的辅助重载:
static bool endsWith(const std::string& str, const char* suffix, unsigned suffixLen)
{
return str.size() >= suffixLen && 0 == str.compare(str.size()-suffixLen, suffixLen, suffix, suffixLen);
}
static bool endsWith(const std::string& str, const char* suffix)
{
return endsWith(str, suffix, std::string::traits_type::length(suffix));
}
static bool startsWith(const std::string& str, const char* prefix, unsigned prefixLen)
{
return str.size() >= prefixLen && 0 == str.compare(0, prefixLen, prefix, prefixLen);
}
static bool startsWith(const std::string& str, const char* prefix)
{
return startsWith(str, prefix, std::string::traits_type::length(prefix));
}
IMO, c++ strings are clearly dysfunctional, and weren't made to be used in real world code. But there is a hope that this will get better at least.
IMO,C++ 字符串显然是功能失调的,不能用于现实世界的代码。但至少有希望这会变得更好。
回答by Tom
I know the question's for C++, but if anyone needs a good ol' fashioned C function to do this:
我知道这个问题是针对 C++ 的,但是如果有人需要一个好的老式 C 函数来做到这一点:
/* returns 1 iff str ends with suffix */
int str_ends_with(const char * str, const char * suffix) {
if( str == NULL || suffix == NULL )
return 0;
size_t str_len = strlen(str);
size_t suffix_len = strlen(suffix);
if(suffix_len > str_len)
return 0;
return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len );
}
回答by xtofl
The std::mismatch
method can serve this purpose when used to backwards iterate from the end of both strings:
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() );
回答by baziorek
In my opinion simplest, C++ solution is:
在我看来,最简单的 C++ 解决方案是:
bool endsWith(const string& s, const string& suffix)
{
return s.rfind(suffix) == (s.size()-suffix.size());
}
回答by Dario
Let a
be a string and b
the string you look for. Use a.substr
to get the last n characters of a
and compare them to b (where n is the length of b
)
让我们a
成为一个字符串和b
您要查找的字符串。使用a.substr
获得的最后n个字符a
,并把它们比作B(其中n是长度b
)
Or use std::equal
(include <algorithm>
)
或使用std::equal
(包括<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());
}
回答by PolarBear
Let me extend Joseph's solutionwith the case insensitive version (online demo)
让我用不区分大小写的版本扩展Joseph 的解决方案(在线演示)
static bool EndsWithCaseInsensitive(const std::string& value, const std::string& ending) {
if (ending.size() > value.size()) {
return false;
}
return std::equal(ending.rbegin(), ending.rend(), value.rbegin(),
[](const char a, const char b) {
return tolower(a) == tolower(b);
}
);
}
回答by Julien Pilet
another option is to use regex. The following code makes the search insensitive to upper/lower case:
另一种选择是使用正则表达式。以下代码使搜索对大小写不敏感:
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
return std::regex_search(str,
std::regex(std::string(suffix) + "$", std::regex_constants::icase));
}
probably not so efficient, but easy to implement.
可能效率不高,但易于实施。