std::string_view starts_with() method
- od 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;
Checks if the string view begins with the given prefix.
The prefix may be one of the following:
-
(1) A string view view
sv
(which may be a result of implicit conversion from anotherstd::basic_string_view
). -
(2) A single character
c
. -
(3) A null-terminated character string view
s
.
All three overloads effectively do
std::basic_string_view<CharT, Traits>(data(), size()).starts_with(x)
where x
is the parameter.
Parameters
s
- a string view view which may be a result of implicit conversion from anotherstd::basic_string_view
c
- a single characters
- a null-terminated character string view
Return value
true
if the string_view begins with the provided prefix, false
otherwise.
Complexity
- (1) Linear in the size of
sv
- O(sv.size()). - (2) Constant - O(1).
- (3) Linear in the size of
s
- O(std::strlen(s)).
Notes
Feature testing macro: __cpp_lib_starts_ends_with
.
Example
#include <iostream>
#include <string_view>
template <typename PrefixType>
void test_prefix_print(const std::string_view& str, PrefixType prefix)
{
std::cout << '\'' << str << "' starts with '" << prefix << "': " <<
str.starts_with(prefix) << '\n';
}
int main()
{
std::boolalpha(std::cout);
auto helloWorld = std::string_view("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
Hover to see the original license.