名前空間
変種
操作

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

From 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

3つのオーバーロードはすべて return find(x) != npos; と等価です。ここで x はパラメータです。

目次

[編集] パラメータ

sv - 別の std::basic_string からの暗黙的な変換の結果である可能性のある文字列ビュー
文字 - 単一の文字
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'

[編集] 関連項目

文字列が指定された接頭辞で始まるかをチェックする
(public member function) [編集]
(C++20)
文字列が指定された接尾辞で終わるかをチェックする
(public member function) [編集]
指定された部分文字列が最初に現れる位置を見つける
(public member function) [編集]
部分文字列を返す
(public member function) [編集]
(C++23)
string viewが指定された部分文字列または文字を含むかチェックする
(std::basic_string_view<CharT,Traits> の公開メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)