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

📅  最后修改于: 2023-12-03 15:05:22.215000             🧑  作者: Mango

std::string::find_last_of()

在C++中,std::string::find_last_of()是一个查找字符串中最后一个出现的某个字符的函数。这个函数返回一个整数表示查找到的字符在字符串中的位置,如果没有找到,则返回std::string::npos

基本语法
size_t find_last_of (const string& str, size_t pos = npos) const noexcept;
size_t find_last_of (const char* s, size_t pos = npos) const;
size_t find_last_of (const char* s, size_t pos, size_t n) const;
size_t find_last_of (char c, size_t pos = npos) const noexcept;

其中:

  • str:要查找的字符串,作为const std::string&传递;
  • pos:查找的起始位置,从字符串的起始位置开始算起,可以省略,默认值为std::string::npos,表示从最后一个位置开始查找;
  • s:要查找的字符数组,作为const char*传递;
  • n:查找s中前n个字符。
示例

以下是一个使用std::string::find_last_of()函数的例子:

#include <iostream>
#include <string>

int main()
{
    std::string str = "hello world";
    char ch = 'o';

    int pos = str.find_last_of(ch); // 查找最后一个字符'o'的位置
    if (pos != std::string::npos)
        std::cout << "The last '" << ch << "' is at position " << pos << std::endl;

    return 0;
}

输出结果为:

The last 'o' is at position 7

在本例中,我们查找字符数组中最后一个出现的字符'o',并输出它在字符串中的位置。有关更多用法,请参阅C++官方文档。