(一)String 类提供了六种查找函数
(1)find rfind
例一
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str="01234567890000";
int a;
a=str.find("0");
cout<<a<<endl;//返回0
a=str.find("123");
cout<<a<<endl;//返回1
a=str.find("456");
cout<<a<<endl;//返回4
system("Pause");
return 0;
}
查到第一个就返回,不管以后有几个,字符串就返回第一个字符的位置,从0开始数,操作全都返回 string::size_type 类型的值,以下标形式标记查找匹配所发生的位置;或者返回一个名为 string::npos 的特殊值,说明查找没有匹配。 npos = -1代表字符串索引号的末尾一个。或者表示无效索引号
hyhjTag.find("|" + acitveTag + "|") != string::npos 说明如果hyhjTag等于activeTag
rfind同理只不过是反向查找
(二)find_first_of find_last_of find_first_not_of() find_last_not_of()
find_first_of(), find_last_of(), find_first_not_of(), find_last_not_of()作用是查找 字符串中 任一个字符 满足的查找条件string snake1("cobra");int where = snake1.find_first_of("hark");返回3 因为 "hark"中 各一个字符 在 snake1--cobra 中第一次出现的是 字符'r'(3为 cobra 中'r'的索引)同理:int where = snake1.find_last_of("hark");返回4 因为 "hark"中 各一个字符 在 snake1--cobra 中最后一次出现的是 字符'a'(3为 cobra 中'r'的索引)例二#include<iostream> #include<string> using namespace std; void main() { string s("Study hard and make progress every day!every day!!"); int loc; loc=s.rfind("make",10); cout<<"The word make is at index "<<loc<<endl; loc=s.rfind("make",40); cout<<"the word is at index"<<loc<<endl; loc=s.find_first_of("day"); cout<<"the word day(first) is at index"<<loc<<endl; } 输出结果:The word make is at index -1 the word is at index15 the word day(first) is at index3;//从pos开始从后向前查找字符c在当前串中的位置int rfind(const char *s, int pos = npos) const; int rfind(const string &s,int pos = npos) const; 第一个从 第10个符号开始,向前找 "make" ,因为没有,所以直接返回 -1 第二个从 第40个符号开始, 向前找"make" ,返回 15 第三个从 整个字符串的最想向前找 "day",所以返回 3