cpp / latest / string / basic_string / contains.html /

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

constexpr bool contains( std::basic_string_view<CharT,Traits> sv )
    const noexcept;
(1) (since C++23)
constexpr bool contains( CharT c ) const noexcept;
(2) (since C++23)
constexpr bool contains( const CharT* s ) const;
(3) (since C++23)

Checks if the string contains the given substring. The substring may be one of the following:

1) a string view sv (which may be a result of implicit conversion from another std::basic_string).
2) a single character c.
3) a null-terminated character string s.

All three overloads are equivalent to return find(x) != npos;, where x is the parameter.

Parameters

sv - a string view which may be a result of implicit conversion from another std::basic_string
c - a single character
s - a null-terminated character string

Return value

true if the string contains the provided substring, false otherwise.

Notes

Feature testing macro: __cpp_lib_string_contains.

Example

#include <iostream>
#include <string_view>
#include <string>
 
template <typename SubstrType>
void test_substring_print(const std::string& str, SubstrType subs)
{
    std::cout << '\'' << str << "' contains '" << subs << "': " <<
        str.contains(subs) << '\n';
}
 
int main()
{
    std::boolalpha(std::cout);    
    auto helloWorld = std::string("hello world");
 
    test_substring_print(helloWorld, std::string_view("hello"));
 
    test_substring_print(helloWorld, std::string_view("goodbye"));
 
    test_substring_print(helloWorld, 'w');
 
    test_substring_print(helloWorld, 'x');
}

Output:

'hello world' contains 'hello': true
'hello world' contains 'goodbye': false
'hello world' contains 'w': true
'hello world' contains 'x': false

See also

(C++20)
checks if the string starts with the given prefix
(public member function)
(C++20)
checks if the string ends with the given suffix
(public member function)
find characters in the string
(public member function)
returns a substring
(public member function)
(C++23)
checks if the string view contains the given substring or character
(public member function of std::basic_string_view<CharT,Traits>)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/string/basic_string/contains