21xrx.com
2025-03-29 01:20:17 Saturday
文章检索 我的文章 写文章
C++中的find_last_of函数使用方法及示例
2023-06-24 10:16:51 深夜i     28     0
C++ find_last_of函数 使用方法 示例

C++中的find_last_of函数是一个字符串查找函数,用于查找一个字符序列中最后一个出现的指定字符(可以是多个字符中的任意一个)的位置。它的使用方法和示例如下:

使用方法:

find_last_of函数的声明如下:

size_t find_last_of (const string& str, size_t pos = npos) const noexcept;

其中,str是要查找的字符序列,pos是开始查找的位置(默认为npos,即从字符串末尾开始查找)。

示例:

下面是一个使用find_last_of函数查找字符串中最后出现的指定字符的示例:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "hello world";
  int pos = str.find_last_of('l'); //查找最后一个字符'l'的位置
  cout << "The index of last 'l' is: " << pos << endl;
  return 0;
}

输出结果为:

The index of last 'l' is: 9

此示例中,我们声明一个字符串str,并使用find_last_of函数查找最后一个字符‘l’的位置,最终输出了该字符的位置9。除了字符,find_last_of函数还可以查找一个字符串中最后一个出现的指定子串的位置,如下所示:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "hello world";
  string sub = "lo";
  int pos = str.find_last_of(sub); //查找最后一个子串"lo"的位置
  cout << "The index of last \"lo\" is: " << pos << endl;
  return 0;
}

输出结果为:

The index of last "lo" is: 8

此示例中,我们使用了一个字符串子串“lo”,使用find_last_of函数查找在字符串中最后一次出现该子串的位置,输出结果为8。

  
  

评论区

    相似文章