Spec-Zone.ru › C++

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 ch ) const noexcept;
(2) (since C++23)
constexpr bool
    contains( const CharT* s ) const;
(3) (since C++23)

Проверяет, содержит ли строка заданную подстроку. Подстрокой может быть:

1) Строковый вид sv (который может быть результатом неявного преобразования из другой std::basic_string).
2) Одиночный символ ch.
3) Нуль-терминированная строка символов s.

Все три перегрузки эквивалентны return find(x) != npos;, где x — параметр.

Параметры

sv - строковый вид, который может быть результатом неявного преобразования из другой std::basic_string
ch - одиночный символ
s - нуль-терминированная строка символов

Возвращаемое значение

true если строка содержит указанную подстроку, false в противном случае.

Примечания

Макрокоманда проверки наличия функции Значение Std Функция
__cpp_lib_string_contains 202011L (C++23) contains функции

Пример

#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
#include <type_traits>
 
template<typename SubstrType>
void test_substring(const std::string& str, SubstrType subs)
{
    constexpr char delim = std::is_scalar_v<SubstrType> ? '\'' : '\"';
    std::cout << std::quoted(str)
              << (str.contains(subs) ? " contains "
                                     : " does not contain ")
              << std::quoted(std::string{subs}, delim) << '\n';
}
 
int main()
{
    using namespace std::literals;
 
    auto helloWorld = "hello world"s;
 
    test_substring(helloWorld, "hello"sv);
    test_substring(helloWorld, "goodbye"sv);
    test_substring(helloWorld, 'w');
    test_substring(helloWorld, 'x');
}

Вывод:

"hello world" contains "hello"
"hello world" does not contain "goodbye"
"hello world" contains 'w'
"hello world" does not contain 'x'

См. также

starts_with
(C++20)
проверяет, начинается ли строка с данного префикса
(публичный член-функция)
ends_with
(C++20)
проверяет, заканчивается ли строка данным суффиксом
(публичный член-функция)
find
находит первое вхождение заданной подстроки
(публичный член-функция)
substr
возвращает подстроку
(публичный член-функция)
contains
(C++23)
проверяет, содержит ли строковый вид заданную подстроку или символ
(публичный член-функция 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

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API