std::basic_string<CharT,Traits,Allocator>::ends_with_C++中文网

C++ 参考手册

位置:首页 > C++ 参考手册 >字符串库 >std::basic_string > std::basic_string<CharT,Traits,Allocator>::ends_with

检查 string 是否终于给定后缀。后缀可为以下之一:

1) string_view sv (可以是从另一 std::basic_string 隐式转换的结果)。
2) 单个字符 c
3) 空终止字符串 s

所有三个重载等效地返回 std::basic_string_view<CharT, Traits>(data(), size()).ends_with(x) ,其中 x 是参数。

参数

sv - string_view ,可为从另一 std::basic_string 隐式转换的结果
c - 单个字符
s - 空终止字符串

返回值

若 string 终于给定后缀则为 true ,否则为 false 。

示例

#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("goodby"));
 
    test_suffix_print(helloWorld, 'd');
 
    test_suffix_print(helloWorld, 'x');
}

输出:

'hello world' ends with 'world': true
'hello world' ends with 'goodby': false
'hello world' ends with 'd': true
'hello world' ends with 'x': false

参阅