C++中sting的rfind函数返回值

string中的find函数与rfind函数定义如下:

int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置

int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
//查找成功时返回所在位置,失败返回string::npos的值 
int rfind(char c, int pos = npos) const;//从pos开始从后向前查找字符c在当前串中的位置
int rfind(const char *s, int pos = npos) const;
int rfind(const char *s, int pos, int n = npos) const;

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

在实际的程序实现中,rfind的查找截止值并不是pos,而是pos+strlen(c)-1。

#include<iostream>
using namespace std;
int main()
{	
	string st = "1111111111";			//10个字符
	cout<< st.rfind("1111",9) << endl;	//按照定义应返回6,正确
	cout<< st.rfind("1111",7) << endl;	//按照定义应返回4,实际是6
	cout<< st.rfind("1111",5) << endl;	//按照定义应返回2,实际是5
	cout<< st.rfind("1111",2) << endl;	//按照定义应返回-1,实际是2

	return 0;	
}


  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值