关于rfind

rfind全名reversefind

与find相反,

  size_type rfind( const basic_string &str, size_type index );
  size_type rfind( const char *str, size_type index );
  size_type rfind( const char *str, size_type index, size_type num );
  size_type rfind( char ch, size_type index );

 

rfind()函数:

  • 返回最后一个与str中的某个字符匹配的字符,从index开始查找。如果没找到就返回string::npos
  • 返回最后一个与str中的某个字符匹配的字符,从index开始查找,最多查找num个字符。如果没找到就返回string::npos
  • 返回最后一个与ch匹配的字符,从index开始查找。如果没找到就返回string::npos

这里要注意与find不同的地方,rfind是从左往右数index个位置,这里作为基准index,然后从这里开始,从右往左数到第一次出现目标的位置。

find是在基准index从左往右数

例子

#include <cstring>
#include <iostream>

int main()
{
	int loc;
    std::string s = "My cat's breath smells like cat food.";

	loc = s.rfind( "breath", 8 );
	std::cout << "The word breath is at index " << loc << std::endl;
	//-1
    loc = s.rfind( "breath", 9 );
	std::cout << "The word breath is at index " << loc << std::endl;
	//9

    loc = s.rfind( "breath", 20 );
	std::cout << "The word breath is at index " << loc << std::endl;
	//9

	std::string ss = "Hi Bill, I'm ill, so please pay the bill";
	loc = ss.rfind("ill");
	std::cout << "The word breath is at index " << loc << std::endl;
	//37
	loc = ss.rfind("ill",20);
	std::cout << "The word breath is at index " << loc << std::endl;
	//13
}


 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值