CppDS.com

C++ 98 11 14 17 20 手册

std::basic_string<CharT,Traits,Allocator>::starts_with

来自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
constexpr bool starts_with( std::basic_string_view<CharT,Traits> sv )
    const noexcept;
(1) (C++20 起)
constexpr bool starts_with( CharT c ) const noexcept;
(2) (C++20 起)
constexpr bool starts_with( const CharT* s ) const;
(3) (C++20 起)

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

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

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

参数

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

返回值

若 string 始于前缀起始则为 true ,否则为 false

示例

#include <iostream>
#include <string_view>
#include <string>
 
template <typename PrefixType>
void test_prefix_print(const std::string& str, PrefixType prefix)
{
    std::cout << '\'' << str << "' starts with '" << prefix << "': " <<
        str.starts_with(prefix) << '\n';
}
 
int main()
{
    std::boolalpha(std::cout);    
    auto helloWorld = std::string("hello world");
 
    test_prefix_print(helloWorld, std::string_view("hello"));
 
    test_prefix_print(helloWorld, std::string_view("goodbye"));
 
    test_prefix_print(helloWorld, 'h');
 
    test_prefix_print(helloWorld, 'x');
}

输出:

'hello world' starts with 'hello': true
'hello world' starts with 'goodby': false
'hello world' starts with 'h': true
'hello world' starts with 'x': false

参阅

(C++20)
检查 string 是否终于给定后缀
(公开成员函数)
检查 string_view 是否始于给定前缀
(std::basic_string_view<CharT,Traits> 的公开成员函数)
(C++20)
检查 string_view 是否终于给定后缀
(std::basic_string_view<CharT,Traits> 的公开成员函数)
比较二个字符串
(公开成员函数)
返回子串
(公开成员函数)
关闭