名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
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> 的公共成員函式) [編輯]