Namespaces
Variants

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

From cppreference.net
std::basic_string
constexpr bool
contains ( std:: basic_string_view < CharT,Traits > sv ) const noexcept ;
(1) (C++23부터)
constexpr bool
contains ( CharT ch ) const noexcept ;
(2) (C++23부터)
constexpr bool
contains ( const CharT * s ) const ;
(3) (C++23부터)

문자열이 주어진 부분 문자열을 포함하는지 확인합니다. 부분 문자열은 다음 중 하나일 수 있습니다:

1) 문자열 뷰 sv (이는 다른 std::basic_string 에서 암시적 변환의 결과일 수 있음).
2) 단일 문자 ch .
3) 널 종료 문자열 s .

세 가지 오버로드는 모두 return find ( x ) ! = npos ; 와 동일하며, 여기서 x 는 매개변수입니다.

목차

매개변수

sv - 다른 std::basic_string 에서 암시적 변환의 결과일 수 있는 문자열 뷰
ch - 단일 문자
s - 널 종료 문자열

반환값

true 문자열이 제공된 부분 문자열을 포함하는 경우, false 그렇지 않은 경우.

참고 사항

기능 테스트 매크로 표준 기능
__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'

참고 항목

문자열이 주어진 접두사로 시작하는지 확인합니다
(public member function)
(C++20)
문자열이 주어진 접미사로 끝나는지 확인합니다
(public member function)
주어진 부분 문자열의 첫 번째 발생 위치를 찾습니다
(public member function)
부분 문자열을 반환합니다
(public member function)
(C++23)
문자열 뷰가 주어진 부분 문자열이나 문자를 포함하는지 확인합니다
(public member function of std::basic_string_view<CharT,Traits> )