std::string ends_with() 方法
- 自 C++20 起
// (1) Const version only
constexpr bool ends_with( std::basic_string_view<CharT,Traits> sv ) const noexcept;
// (2) Const version only
constexpr bool ends_with( CharT c ) const noexcept;
// (3) Const version only
constexpr bool ends_with( const CharT* s ) const;
检查字符串是否以给定后缀结尾。
前缀可以是以下之一
-
(1) 字符串视图
sv
(可能是从另一个std::basic_string
隐式转换的结果)。 -
(2) 一个字符
c
。 -
(3) 以 null 结尾的字符串
s
。
所有三个重载实际上都执行
std::basic_string_view<CharT, Traits>(data(), size()).ends_with(x)
其中 x
是参数。
参数
s
- 字符串视图,可能是从另一个std::basic_string
隐式转换的结果c
- 一个字符s
- 以 null 结尾的字符串
返回值
如果字符串以提供的前缀结尾,则为 true
,否则为 false
。
复杂度
- (1) 线性于
sv
的大小 - O(sv.size())。 - (2) 常数 - O(1)。
- (3) 线性于
s
的大小 - O(std::strlen(s))。
备注
功能测试宏:__cpp_lib_ends_ends_with
。
示例
#include <iostream>
#include <string_view>
#include <string>
template <typename SuffixType>
void test_suffix_print(const std::string& str, SuffixType suffix)
{
std::cout << '\'' << str << "' ends with '" << suffix << "': " <<
str.ends_with(suffix) << '\n';
}
int main()
{
std::boolalpha(std::cout);
auto helloWorld = std::string("hello world");
test_suffix_print(helloWorld, std::string_view("world"));
test_suffix_print(helloWorld, std::string_view("goodbye"));
test_suffix_print(helloWorld, 'd');
test_suffix_print(helloWorld, 'x');
}
输出
'hello world' ends with 'world': true
'hello world' ends with 'goodbye': false
'hello world' ends with 'd': true
'hello world' ends with 'x': false