21xrx.com
2024-09-20 00:36:46 Friday
登录
文章检索 我的文章 写文章
C++中string的rfind函数
2023-07-05 01:22:54 深夜i     --     --
C++ string rfind函数

在C++中,字符串(string)是一个经常被使用的数据类型。C++提供了很多方便的字符串处理函数,其中之一就是rfind函数。

rfind函数的作用是在一个字符串中从后往前查找指定的子串,并返回子串第一次出现的位置。如果子串不存在,则返回-1。

rfind函数的语法如下:


int rfind(char c, int pos = npos) const noexcept;

int rfind(const char* s, int pos = npos) const;

int rfind(const char* s, int pos, int n) const;

int rfind(const string& str, int pos = npos) const noexcept;

其中,第一个参数是要查找的子串,可以是字符(char)或字符串(const char*);第二个参数是要开始查找的位置,默认值为npos,表示从后往前查找整个字符串。

下面是一个示例代码:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "hello world";

  int pos1 = str.rfind('o');

  int pos2 = str.rfind("world");

  int pos3 = str.rfind("world", 6, 3);

  cout << pos1 << endl; // 7

  cout << pos2 << endl; // 6

  cout << pos3 << endl; // -1

  return 0;

}

以上示例代码中,分别使用了字符、字符串和指定起始位置的字符串三种不同的方式进行查找。

需要注意的是,rfind函数返回的是一个整数,表示子串在字符串中的位置。如果要判断子串是否存在,则可以根据返回值是否为-1进行判断。

总之,rfind函数是一种十分方便的字符串处理函数,可以很方便地在字符串中查找指定的子串,对于字符串操作和处理非常有帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复