std::string_view contains() method
- since C++23
// (1) Const version only
constexpr bool contains( basic_string_view sv ) const noexcept;
// (2) Const version only
constexpr bool contains( CharT c ) const noexcept;
// (3) Const version only
constexpr bool contains( const CharT* s ) const;
Checks if the string view contains the given substring, where
- (1) The substring is a string view.
- (2) The substring is a single character.
- (3) The substring is a null-terminated character string.
All three overloads effectively do
find(x) != npos;
where x
is the parameter.
Parameters
sv
- a string viewc
- a single characters
- a null-terminated character string
Return value
true
if the view contains the provided substring, false
otherwise.
Complexity
important
This section requires improvement. You can help by editing this doc page.
Notes
Feature testing macro: __cpp_lib_string_view_contains
.
Example
#include <iostream>
#include <string_view>
auto main() -> int
{
using namespace std::literals;
std::cout
<< std::boolalpha
// bool contains(basic_string_view x) const noexcept;
<< "https://cppreference.com"sv.contains("cpp"sv) << ' ' // true
<< "https://cppreference.com"sv.contains("java"sv) << ' ' // false
// bool contains(CharT x) const noexcept;
<< "C++23"sv.contains('+') << ' ' // true
<< "C++23"sv.contains('-') << ' ' // false
// bool contains(const CharT* x) const;
<< std::string_view("basic_string_view").contains("string") << ' ' // true
<< std::string_view("basic_string_view").contains("String") << ' ' // false
<< '\n';
}
Output
true false true false true false
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.