string类提供了6个不同的搜索函数。每个函数有4个重载版本。每个搜索操作都返回一个string::size_type值,表示匹配发生位置的值。如果搜索失败,则返回一个string::npos的static 成员。标准库将npos定义为一个const string::size_type 类型,并初始化为值-1。
(1)find()函数
string name("AnnaBelle");
auto pos1 = name.find("Anna");// pos1 = 0
搜索是大小写敏感的。
(2) find_first_of() 和 find_first_not_of()函数
string numbens("0123456789");
string name("r2d2");
auto pos2 = name.find_first_of(numbers);// pos2 = 1,即name中的第一个数字
string dept("03714p3");
auto pos3 = dept.find_first_not_of(numbers);
//pos3 = 5,即字符 'p'的下标
(3) find_last_of()
当然,也可以指定搜索的开始位置、
string::size_type pos = 0;
//每步循环查找name 中的下一个数
while((pos = name.find_first_of(numbers,pos) != string::npos){
cout<<"found number at index: "<< pos<<" element is " <<
name[pos] <<endl;
++pos;//移动到下一个字符
}
(4)逆向搜索 rfind() 从有往左搜索