函数说明
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;
}
测试结果
结果可通过调试得出。