📜  std :: 字符串:: find_last_of在C++中的示例

📅  最后修改于: 2021-05-30 10:47:34             🧑  作者: Mango

std :: 字符串:: find_last_of是一个字符串类成员函数,用于查找字符串中任何字符最后一次出现的索引。如果字符存在于字符串,则它返回该字符在字符串最后一次出现的索引,否则返回字符串:: npos

头文件:

#include < string >

模板类

template < class T >
size_type
    find_last_of(const T& t, 
                 size_type pos = npos ) const noexcept();

语法1:

find_last_of(char ch)

参数:此函数需要一个给定的字符并返回该字符的最后出现的位置。

下面是说明字符串:: find_last_of()的程序

// C++ program to illustrate string::find_last_of
#include 
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
  
    // Given String
    string str("Welcome to GeeksforGeeks!");
  
    // Character to be found
    char ch = 'e';
  
    // To store the index of last
    // character found
    size_t found;
  
    // Function to find the las
    // character ch in str
    found = str.find_last_of(ch);
  
    // If string doesn't have
    // character ch present in it
    if (found == string::npos) {
        cout << "Character " << ch
             << " is not present in"
             << " the given string.";
    }
  
    // Else print the last position
    // of the character
    else {
        cout << "Character " << ch
             << " is found at index: "
             << found << endl;
    }
}
输出:
Character e is found at index: 21

语法2:

find_last_of(char ch, size_t position)

参数:该函数采用给定的字符和索引,直到执行搜索为止。它返回该字符最后一次出现的位置。

下面是说明字符串:: find_last_of()的程序

// C++ program to illustrate string::find_last_of
#include 
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
  
    // Given String
    string str("Welcome to GeeksforGeeks!");
  
    // Character to be found
    char ch = 'e';
  
    // To store the index of last
    // character found
    size_t found;
  
    // Position till search is performed
    int pos = 10;
  
    // Function to find the last
    // character ch in str[0, pos]
    found = str.find_last_of(ch, pos);
  
    // If string doesn't have
    // character ch present in it
    if (found == string::npos) {
        cout << "Character " << ch
             << " is not present in"
             << " the given string.";
    }
  
    // Else print the last position
    // of the character
    else {
        cout << "Character " << ch
             << " is found at index: "
             << found << endl;
    }
}
输出:
Character e is found at index: 6

参考: http : //www.cplusplus.com/reference/字符串/字符串/ find_last_of /

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。