std::string starts_with() 方法
- 自 C++20 起
// (1) Const version only
constexpr bool starts_with( std::basic_string_view<CharT,Traits> sv ) const noexcept;
// (2) Const version only
constexpr bool starts_with( CharT c ) const noexcept;
// (3) Const version only
constexpr bool starts_with( const CharT* s ) const;
检查字符串是否以给定前缀开头。
前缀可以是以下之一
-
(1) 字符串视图
sv
(可能是从另一个std::basic_string
隐式转换的结果)。 -
(2) 一个字符
c
。 -
(3) 以 null 结尾的字符串
s
。
所有三个重载实际上都执行
std::basic_string_view<CharT, Traits>(data(), size()).starts_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_starts_ends_with
。
示例
#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 'goodbye': false
'hello world' starts with 'h': true
'hello world' starts with 'x': false