basic::string的查找字符的方法find_first_of函数与find_last_of函数-------02

函数说明

find_first_of() 函数可实现在源串中搜索某字符串的功能,该函数的返回值是被搜索字符串的第 1 个字符第 1 次出现的下标(位置)。若查找失败,则返回 npos。
find_last_of() 函数同样可实现在源串中搜索某字符串的功能。与 find_first_of() 函数所不同的是,该函数的返回值是被搜索字符串的最后 1 个字符的下标(位置)。若查找失败,则返回 npos。

函数原型

	//参数_Count的意义目前还不清楚,如有知道的,麻烦留言评论,共同进步。
	size_type find_first_of (const value_type* _Ptr, size_type _Off = 0) const;
	size_type find_first_of (const value_type* _Ptr, size_type_Off, size_type_Count) const;
	size_type find_first_of (const basic_string & _Str, size_type_Off = 0) const;
	size_type find_last_of (value_type _Ch, size_type_Off = npos) const;
	size_type find_last_of (const value_type* _Ptr, size_type_Off = npos) const;
	size_type find_last_of (const value_type* _Ptr, size_type _Off, size_type _Count) const;
	size_type find_last_of (const basic_string& _Str, size_type_Off = npos) const;

各参数的含义与上一篇文章basic::string的查找字符的方法find(),rfind()-------01中的find函数相同,用法也相同。

测试代码

#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.");
	int length = str.length();


	string::size_type m = str.find_first_of('P', 0);//4
	string::size_type rm = str.find_last_of('P', (length - 1));//21
	cout << "find_first_of (): The position (forward) of 'P' is: " << (int)m << endl;
	cout << "find_last_of (): The position (reverse) of 'P' is: " << (int)rm << endl;


	string::size_type n = str.find_first_of("some", 0);//5
	string::size_type rn = str.find_last_of("some", (length - 1));//51
	cout << "find_first_of(): The position (forward) of 'some' is: " << (int)n << endl;
	cout << "find_last_of(): The position (reverse) of 'some' is: " << (int)rn << endl;


	string::size_type mo = str.find_first_of("drugs", 0, 5);//8
	string::size_type rmo = str.find_last_of("drugs", (length - 1), 5);//48
	cout << "find_first_of () : The position (forward) of 'drugs' is: " << (int)mo << endl;
	cout << "find_last_of () : The position (reverse) of 'drugs' is: " << (int)rmo << endl;


	string::size_type no = str.find_first_of(str_ch, 0);//8
	string::size_type rno = str.find_last_of(str_ch, (length - 1));//48
	cout << "find_first_of() : The position of 'for' is: " << (int)no << endl;
	cout << "find_last_of () : The position of 'for' is: " << (int)rno << endl;
	return 0;
}

测试结果

在这里插入图片描述
结果可通过调试得出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值