std::string starts_with() method
- since 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 begins with the given prefix.
The prefix may be one of the following:
-
(1) A string view
sv
(which may be a result of implicit conversion from anotherstd::basic_string
). -
(2) A single character
c
. -
(3) A null-terminated character string
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 which may be a result of implicit conversion from anotherstd::basic_string
c
- a single characters
- a null-terminated character string
Return value
true
if the string 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>
#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
Hover to see the original license.