- string[meta header]
- std[meta namespace]
- basic_string[meta class]
- function[meta id-type]
size_type find(const basic_string& str, size_type pos = 0) const; // (1) C++03
size_type find(const basic_string& str, size_type pos = 0) const noexcept; // (1) C++11
size_type find(const charT* s, size_type pos, size_type n) const; // (2)
size_type find(const charT* s, size_type pos = 0) const; // (3)
size_type find(charT c, size_type pos = 0) const; // (4)
size_type find(std::basic_string_view<charT, traits> sv,
size_type pos = 0) const noexcept; // (5) C++17
template <class T>
size_type find(const T& t, size_type pos = 0) const noexcept(see below); // (5) C++20
指定した文字列を検索する。
- (5) :
is_convertible_v
<const T&,
basic_string_view
<charT, traits>>
がtrue
であることis_convertible_v
<const T&, const charT*>
がfalse
であること
- (3) :
s
は少なくともtraits_type::length(s) + 1
の要素を持つcharT
の配列を指していること。
- (1)
pos
以降で最初にstr
と一致する位置を返す。 - (2)
pos
以降で最初にs
と一致する位置を返す。s
は長さn
の文字列へのポインタである。 - (3) (2) と同様だが、こちらは NULL 終端の文字列を扱う。
- (4)
pos
以降で最初にc
と一致する位置を返す。 - (5) :
- C++17 :
pos
以降で最初にsv
と一致する位置を返す。 - C++20 :
basic_string_view<charT, traits> sv = t;
として変数sv
を作成し、pos
以降で最初にsv
と一致する位置を返す。
- C++17 :
見つかればその位置を返し、見つからない場合は basic_string::npos
を返す。
- (1) 投げない
- (5) :
- C++17 : 投げない
- C++20 :
noexcept
内の式は、以下と等価であるis_nothrow_convertible_v<const T&, basic_string_view<charT, traits>>
- is_nothrow_convertible_v[link /reference/type_traits/is_nothrow_convertible.md]
- basic_string_view[link /reference/string_view/basic_string_view.md]
- 文字列の一致は、文字列の各文字について
traits_type::eq()
を用いて検査される。
例えば、(1) の形式の場合、以下のような条件を満たす最小のxpos
を求める。pos <= xpos
かつxpos + str.size() <= size()
0 <= I
かつI < str.size()
を満たす全てのI
について、traits_type::eq(at(xpos + I), str.at(I))
- (3) の形式の場合、
s
の文字列長はtraits_type::length(s)
で求められる。
#include <iostream>
#include <string>
int main()
{
const std::string s("hello, world. welcome to C++ world.");
const std::string find_word("world");
std::string::size_type pos = s.find(find_word);
while (pos != std::string::npos) {
std::cout << pos << std::endl;
pos = s.find(find_word, pos + find_word.length());
}
}
- find[color ff0000]
- find_word.length()[link length.md]
7
29
(1) 以外の形式は、(1) の形式を使用して実装することができる。
// (2)
template <class charT, class traits, class Allocator>
size_type basic_string<charT, traits, Allocator>::find(const charT* s, size_type pos, size_type n) const
{
return find(std::basic_string(s, n), pos);
}
// (3)
template <class charT, class traits, class Allocator>
size_type basic_string<charT, traits, Allocator>::find(const charT* s, size_type pos = 0) const
{
return find(std::basic_string(s), pos);
}
// (4)
template <class charT, class traits, class Allocator>
size_type basic_string<charT, traits, Allocator>::find(charT c, size_type pos = 0) const
{
return find(std::basic_string(1, c), pos);
}
名前 | 説明 |
---|---|
search |
指定された最初のサブシーケンスを検索する |
find |
指定された値を検索する |