共用方式為


basic_string::find_first_of (STL Samples)

說明如何使用 basic_string::find_first_of Visual C++ 標準樣板程式庫 (STL) 函式。

size_type find_first_of(
   const basic_string& _X,
   size_type iPos = 0
);
size_type find_first_of(
   const element_type *_S,
   size_type iPos,
   size_type cElementsIn_S
);
size_type find_first_of(
   const element_type *_S,
   size_type iPos = 0
);
size_type find_first_of(
   element_type _C,
   size_type iPos = 0
);

備註

注意事項注意事項

在原型中的類別/參數名稱不相符的標頭檔中的版本。某些已修改以提高可讀性。

成員函式每個找到的第一個 (最低的位置) 或位置之後的受控制序列的項目 iPos ,比對任何一個剩下的運算元所指定的運算元序列中的項目。 如果成功,它會傳回位置。 否則,函數會傳回 npos。 傳回這個位置是 0 (零) 為基礎。 Npos 傳回值是特殊的值,指出沒有任何項目找。

範例

// main.cpp
// compile with: /EHsc
//
// Functions:
//
//    string::find_first_of() - find the first instance in the
//         controlled string of any of the elements specified by the
//         parameters. The search begins at an optionally-supplied
//         position in the controlled string.

#include <string>
#include <iostream>

using namespace std ;

int main()
{
    string str1("Heartbeat");
    string str2("abcde");
    size_t iPos = 0;

    cout << "The string to search is '" << str1.c_str() << "'"
         << endl;

    // find the first instance in str1 of any characters in str2
    iPos = str1.find_first_of (str2, 0);  // 0 is default position

    cout << "Element in '" << str2.c_str() << "' found at position "
         << iPos << endl;

    // start looking in the third position...
    iPos = str1.find_first_of (str2, 2);

    cout << "Element in '" << str2.c_str() << "' found at position "
         << iPos << endl;

    // use an array of the element type as the set of elements to
    // search for; look for anything after the fourth position
    char achVowels[] = {'a', 'e', 'i', 'o', 'u'};
    iPos = str1.find_first_of (achVowels, 4, sizeof(achVowels));

    cout << "Element in '";
    for (int i = 0; i < sizeof (achVowels); i++)
        cout << achVowels[i];
    cout << "' found at position " << iPos << endl;

    // use a string literal to specify the set of elements
    char szVowels[] = "aeiou";
    iPos = str1.find_first_of (szVowels, 0);  // 0 is default position

    cout << "Element in '" << szVowels << "' found at position "
         << iPos << endl;

    // look for a specific character beginning in the third position
    iPos = str1.find_first_of ('e', 2);

    cout << "'e' found at position " << iPos << endl;
}

Output

The string to search is 'Heartbeat'
Element in 'abcde' found at position 1
Element in 'abcde' found at position 2
Element in 'aeiou' found at position 6
Element in 'aeiou' found at position 1
'e' found at position 6

需求

標頭: <string>

請參閱

概念

標準樣板程式庫範例