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

出自cppreference.com
 
 
 
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) 單個字符 c
3) 空終止字符串 s

所有三個重載都等價於 return find(x) != npos;,其中 x 為形參。

參數

sv - 字符串視圖,可能為從另一 std::basic_string 隱式轉換的結果
c - 單個字符
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) ? " 包含 "
                                     : " 不包含 ")
              << 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' 包含 "hello"
'hello world' 不包含 "goodbye"
'hello world' 包含 'w'
'hello world' 不包含 'x'

參閱

檢查字符串是否始於給定前綴
(公開成員函數) [編輯]
(C++20)
檢查字符串是否終於給定後綴
(公開成員函數) [編輯]
尋找給定子串的首次出現
(公開成員函數) [編輯]
返回子串
(公開成員函數) [編輯]
(C++23)
檢查字符串視圖是否含有給定的子串或字符
(std::basic_string_view<CharT,Traits> 的公開成員函數) [編輯]