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

来自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
constexprbool
    contains(std::basic_string_view<CharT,Traits> sv )constnoexcept;
(1) (C++23 起)
constexprbool
    contains( CharT ch )constnoexcept;
(2) (C++23 起)
constexprbool
    contains(const CharT* s )const;
(3) (C++23 起)

检查字符串是否含有给定子串。子串可以是下列三种之一:

1) 字符串视图 sv(可能为从另一 std::basic_string 隐式转换的结果)。
2) 单个字符 c
3) 空终止字符串 s

所有三个重载都等价于 return find(x)!= npos;,其中 x 为形参。

目录

[编辑]参数

sv - 字符串视图,可能为从另一 std::basic_string 隐式转换的结果
c - 单个字符
s - 空终止字符串

[编辑]返回值

若字符串含有给定子串则为 true,否则为 false

[编辑]注解

功能特性测试标准功能特性
__cpp_lib_string_contains202011L(C++23)contains 函数

[编辑]示例

#include <iomanip>#include <iostream>#include <string>#include <string_view>#include <type_traits>   template<typename SubstrType>void test_substring(conststd::string& str, SubstrType subs){constexprchar delim =std::is_scalar_v<SubstrType>?'\'':'\"';std::cout<<std::quoted(str)<<(str.contains(subs)?" 包含 ":" 不包含 ")<<std::quoted(std::string{subs}, delim)<<'\n';}   int main(){usingnamespace 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' 包含 "hello" 'hello world' 不包含 "goodbye" 'hello world' 包含 'w' 'hello world' 不包含 'x'

[编辑]参阅

检查字符串是否始于给定前缀
(公开成员函数)[编辑]
(C++20)
检查字符串是否终于给定后缀
(公开成员函数)[编辑]
寻找给定子串的首次出现
(公开成员函数)[编辑]
返回子串
(公开成员函数)[编辑]
(C++23)
检查字符串视图是否含有给定的子串或字符
(std::basic_string_view<CharT,Traits> 的公开成员函数)[编辑]
close