basic::string的查找字符的方法find(),rfind()-------01

学习basic::string对象的查找方法。

对两个方法中的_Count参数的解释:find(“drugs”, 0, 5),此时第三个参数为5,恰好与第一个参数的长度相同,此时该函数的有效匹配子串为"drugs"; 当第三个参数为4时,小于第一个参数的长度,此时该函数的有效匹配子串为"drug";当第三个参数大于第一个参数的长度时,该函数错误,返回值为-1.

	//size_type为无符号整型unsigned int
函数原型:
	size_type find (value_type _Chr, size_type _Off = 0) const;
	//find()函数的第1个参数是被搜索的字符、第2个参数是在源串中开始搜索的下标位置
	size_type find (const value_type* _Ptr , size_type _Off = 0) const;
	//find()函数的第1个参数是被搜索的字符串,第2个参数是在源串中开始搜索的下标位置
	size_type find (const value_type* _Ptr, size_type _Off = 0, size_type _Count) const;
	//第1个参数是被搜索的字符串,第2个参数是源串中开始搜索的下标,第3个参数是关于第1个参数中要匹配的个数,从左向右算,但第三个参数值不能超过第一个参数的长度,否则返回-1
	size_type find (const basic_string& _Str, size_type _Off = 0) const;
	//第1个参数是被搜索的字符串,第2参数是在源串中开始搜索的下标位置

//rfind()与find函数原型及参数相同,只不过是向前查找,find函数为向后查找

/*
	若查找 find() 函数和其他函数没有搜索到期望的字符(或子串),则返回 npos;
	若搜索成功,则返回搜索到的第 1 个字符或子串的位置。其中,npos 是一个无符号整数值,初始值为 -1。
	当搜索失败时, npos 表示“没有找到(not found)”或“所有剩佘字符”。
*/

测试代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{

	string str_ch(" for");
	string str("Hi, Peter, I'm sick. Please bought some drugs for me.");
	
	string::size_type m = str.find('P', 5);
	string::size_type rm = str.rfind('P', 5);
	cout << "find() : The position (forward) of 'P' is: " << (int)m << endl;
	cout << "rfind(): The position (reverse) of 'P' is: " << (int)rm << endl;

	string::size_type n = str.find("some", 0);
	string::size_type rn = str.rfind("some", 0);
	cout << "find () : The position (forward) of 'some' is: " << (int)n << endl;
	cout << "rfind () : The position (reverse) of 'some' is: " << (int)rn << endl;

	
	string::size_type mo = str.find(" drugs", 0, 5);
	string::size_type rmo = str.rfind(" drugs", 0, 5);//-1
	cout << "find(): The position (forward) of 'drugs' is: " << (int)mo << endl;
	cout << "rfind(): The position (reverse) of 'drugs' is: " << (int)rmo << endl;
	
	
	string::size_type no = str.find(str_ch, 0);
	string::size_type rno = str.rfind(str_ch, 0);
	cout << "find (): The position of 'for' is: " << (int)no << endl;
	cout << "rfind(): The position of 'for' is: " << (int)rno << endl;
	system("pause");
	return 0;
}

测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值