public member function
<string>

std::basic_string::find

string (1)
size_type find (const basic_string& str, size_type pos = 0) const;
c-string (2)
size_type find (const charT* s, size_type pos = 0) const;
buffer (3)
size_type find (const charT* s, size_type pos, size_type n) const;
character (4)
size_type find (charT c, size_type pos = 0) const;
string (1)
size_type find (const basic_string& str, size_type pos = 0) const noexcept;
c-string (2)
size_type find (const charT* s, size_type pos = 0) const;
buffer (3)
size_type find (const charT* s, size_type pos, size_type n) const;
character (4)
size_type find (charT c, size_type pos = 0) const noexcept;
在字串中查詢首次出現
basic_string中搜索引數指定的序列首次出現的位置。

當指定pos時,搜尋僅包括位置pos或之後的字元,忽略任何可能包含pos之前字元的匹配項。

該函式使用traits_type::eq來確定字元的等價性。

請注意,與成員find_first_of不同,當搜尋多個字元時,僅匹配其中一個字元是不夠的,整個序列必須匹配。

引數

str
另一個要搜尋的basic_string
pos
搜尋中要考慮的字串中第一個字元的位置。
如果大於字串長度,則該函式永遠找不到匹配項。
注意:第一個字元用值表示0(不是1): A value of0表示搜尋整個字串。
s
指向字元陣列的指標。
如果指定了引數n (3),則要匹配的序列是陣列中的前n個字元。
否則(2),期望一個以 null 結尾的序列:要匹配的序列的長度由第一個 null 字元確定。
n
要匹配的字元序列的長度。
c
要搜尋的單個字元。

charTbasic_string 的字元型別(即,它的第一個模板引數)。
成員型別size_type是一種無符號整型型別。

返回值

第一個匹配項的第一個字元的位置。
如果未找到匹配項,該函式將返回basic_string::npos

成員型別size_type是一種無符號整型型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// string::find
#include <iostream>
#include <string>

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::string::size_type found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

  return 0;
}

請注意如何使用引數pos來搜尋同一搜尋字串的第二個例項。 輸出
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.


複雜度

未指定,但通常與length()-pos乘以要匹配的序列的長度(最壞情況)。

迭代器有效性

沒有變化。

資料競爭

該物件被訪問。

異常安全

如果已知s未指向足夠長的陣列,會導致未定義行為
否則,該函式永遠不會丟擲異常(無丟擲保證)。

另見