在STL中,字符串查找可以实现多种功能,例如:
- 搜索单个字符、搜索子串;
- 实现前向搜索、后向搜索;
- 分别实现搜索第一个和最后一个满足条件的字符(或子串);
要明确的一点是,所有查找find()函数的返回值均是size_type类型,即无符号整数类型,该返回值用于表示字符串中元素个数或者字符在字符串中的位置。
find()函数和rfind()函数
find()函数的四种原型如下:
原型 |
功能 |
size_type find(value_type_Chr , size_type_Off = 0 ) const; |
第一个参数是被搜索的字符、第二个参数是在源串中开始搜索的位置
|
size_type find(const value_type*_Ptr , size_type_Off = 0 ) const; |
第一个参数是被搜索的字符串、第二个参数是在源串中开始搜索的位置 |
size_type find(const value_type*_Ptr , size_type_Off = 0 , size_type_Const ) const; |
第一个参数是被搜索的字符串、第二个参数是在源串中开始搜索的位置、第三个参数是第一个参数中用于搜索的字符串长度
|
size_type find(const basic_string&_Str , size_type_Off = 0 ) const; |
第一个参数是被搜索的字符串、第二个参数是在源串中开始搜索的位置 |
rfind()函数的原型和find()函数的原型类似,参数也类似,只不过rfind()适用于逆向查找。
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.");
string::size_type m = str.find('P', 5);
cout << "Example - find() : The position (forward) of 'P' is: " << (int) m << endl;
string::size_type n = str.find(" some", 0);
cout << "Example - find() : The position (forward) of 'some' is: " << (int) n << endl;
string::size_type mo = str.find(" drugs", 0, 5);
cout << "Example - find(): The position (forward) of 'drugs' is: " << (int) mo << endl;
string::size_type no = str.find(str_ch, 0);
cout << "Example - find(): The position of 'for' is: " << (int) no << endl;
cin.get();
}
程序运行结果如下:
Example - find() : The position (forward) of 'P' is: 5
Example - find () : The position (forward) of 'some' is: 35
Example - find(): The position (forward) of 'drugs' is: 40
Example - find (): The position of 'for' is: 46
rfind()函数的使用方法如下:
#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 rm = str.rfind('P', 5);
cout << "Example - rfind(): The position (reverse) of 'P' is: " << (int) rm << endl;
string::size_type rn = str.rfind(" some", 0);
cout << "Example - rfind() : The position (reverse) of 'some' is: " << (int) rn << endl;
string::size_type rmo = str.rfind(" drugs", 0, 5);
cout << "Example - rfind(): The position (reverse) of 'drugs' is: " << (int) rmo << endl;
string::size_type rno = str.rfind(str_ch, 0);
cout << "Example - rfind(): The position of 'for' is: " << (int) rno << endl;
cin.get();
}
程序运行结果如下:
Example - rfind(): The position (reverse) of 'P' is: 5
Example - rfind() : The position (reverse) of 'some' is: -1
Example - rfind(): The position (reverse) of 'drugs' is: -1
Example - rfind(): The position of 'for' is: -1
除此之外,用于搜索的函数还有find_first_of()
、find_last_of()
、find_first_not_of()
和find_last_not_of()
其中find_first_of()
函数可实现在源串中搜索某字符串的功能,该函数的返回值是被搜索字符串的第 1 个字符第 1 次出现的下标(位置)。若查找失败,则返回 npos。
find_last_of()
函数同样可实现在源串中搜索某字符串的功能。与find_first_of()
函数所不同的是,该函数的返回值是被搜索字符串的最后 1 个字符的下标。若查找失败,则返回 npos。
find_first_not_of()
函数可实现在源字符串中搜索与指定字符(串)不相等的第 1 个字符;
find_last_not_of()
函数可实现在源字符串中搜索与指定字符(串)不相等的最后 1 个字符。