std::basic_string<CharT,Traits,Allocator>::contains
来自 cppreference.cn
< cpp | string | basic string
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 否则为假。
[编辑] 注解
特性测试 宏 | 值 | 标准 | 特性 |
---|---|---|---|
__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++20) |
检查字符串是否以给定的后缀结尾 (公共成员函数) |
查找给定子字符串的首次出现 (公共成员函数) | |
返回子字符串 (公共成员函数) | |
(C++23) |
检查字符串视图是否包含给定的子字符串或字符 ( std::basic_string_view<CharT,Traits> 的公共成员函数) |