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'

参见

检查字符串是否以给定前缀开头
(公开成员函数)
(C++20)
检查字符串是否以给定后缀结尾
(公开成员函数)
查找给定子串的首次出现
(公开成员函数)
返回子串
(公开成员函数)
(C++23)
检查字符串视图是否包含给定子串或字符
( std::basic_string_view<CharT,Traits> 的公开成员函数)