size_type find_last_of(const basic_string& str, size_type pos = npos) const; // (1) C++03 size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept; // (1) C++11 size_type find_last_of(const charT* s, size_type pos, size_type n) const; // (2) size_type find_last_of(const charT* s, size_type pos = npos) const; // (3) size_type find_last_of(charT c, size_type pos = npos) const; // (4) size_type find_last_of(std::basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept; // (5) C++17
概要
指定された文字列中のいずれかの文字が出現する最後の場所を検索する。
要件
(3) の形式の場合、s
は少なくとも traits_type::length(s) + 1
の要素を持つ charT
の配列を指していること。
効果
- (1)
pos
より前で最後にstr
内に存在する文字の位置を返す。 - (2)
pos
より前で最後にs
内に存在する文字の位置を返す。s
は長さn
の文字列へのポインタである。 - (3) (2) と同様だが、こちらは NULL 終端の文字列を扱う。
- (4)
pos
より前で最後にc
と一致する文字の位置を返す。 - (5)
pos
より前で最後にsv
内に存在する文字の位置を返す。
戻り値
見つかればその位置を返し、見つからない場合は basic_string::npos
を返す。
例外
- (1) 投げない
- (5) 投げない
備考
- 一致する文字の検索は、指定された文字列の各文字について
traits_type::eq
を使用することで行われる。
例えば、(1) の形式の場合、以下のような条件を満たす最大のxpos
を求める。xpos <= pos
かつxpos < size()
0 <= I
かつI < str.size()
を満たすいずれかのI
について、traits_type::eq(at(xpos), 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 str("world"); // "C++" の "C" 以前で "world" を検索すると、"to" の 2 文字目の "o" が見つかる std::cout << s.find_last_of(str, 25) << std::endl; // "Hello," の "," 以前で ",.+" を検索すると、"," が見つかる std::cout << s.find_last_of(",.+", 5) << std::endl; // 標準の char_traits では大文字と小文字は区別されるため、"world" の "w" は見つからずに "Welcome" の "W" が見つかる std::cout << s.find_last_of('W') << std::endl; }
出力
23
5
14
実装例
(1) 以外の形式は、(1) の形式を使用して実装することができる。
// (2) template <class charT, class traits, class Allocator> size_type basic_string<charT, traits, Allocator>::find_last_of(const charT* s, size_type pos, size_type n) const { return find_last_of(std::basic_string(s, n), pos); } // (3) template <class charT, class traits, class Allocator> size_type basic_string<charT, traits, Allocator>::find_last_of(const charT* s, size_type pos = npos) const { return find_last_of(std::basic_string(s), pos); } // (4) template <class charT, class traits, class Allocator> size_type basic_string<charT, traits, Allocator>::find_last_of(charT c, size_type pos = npos) const { return find_last_of(std::basic_string(1, c), pos); }