std::string contains() 方法
- 自 C++23 起
// (1) Const version only
constexpr bool contains( std::basic_string_view<CharT,Traits> sv ) const noexcept;
// (2) Const version only
constexpr bool contains( CharT c ) const noexcept;
// (3) Const version only
constexpr bool contains( const CharT* s ) const;
检查字符串是否包含给定的子字符串
前缀可以是以下之一
-
(1) 字符串视图
sv
(可能是从另一个std::basic_string
隐式转换的结果)。 -
(2) 一个字符
c
。 -
(3) 以 null 结尾的字符串
s
。
所有三个重载实际上都执行
find(x) != npos;
其中 x
是参数。
参数
s
- 字符串视图,可能是从另一个std::basic_string
隐式转换的结果c
- 一个字符s
- 以 null 结尾的字符串
返回值
如果字符串包含提供的子字符串,则为true
,否则为false
。
复杂度
重要
本节需要改进。您可以通过编辑此文档页面来帮助我们。
备注
特性测试宏:__cpp_lib_string_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'