1. 基本用法
语法
string的find()函数用于找出字母在字符串中的位置。
find(str,position)
-
str:是要找的元素
-
position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素(不填第二个参数,默认从字符串的开头进行查找)
返回值为目标字符的位置(第一个字符位置为0),当没有找到目标字符时返回npos
举例
//找到目标字符的位置
string s = "hello world!";
cout << s.find("e") << endl;
输出结果:1
//未找到目标字符
string s = "hello world!";
if (s.find("a") == s.npos) {
cout << "not found" << endl;
}
输出结果:not found
//指定查找位置
string s = "hello world!";
cout << s.find("l",5) << endl;
输出结果:9
2. 延伸用法
2.1 找到目标字符第一次出现和最后一次出现的位置
string s = "hello world!";
cout <<s.find_first_of("l") << endl;//第一次出现的位置
cout << s.find_last_of("l") << endl;//最后一次出现的位置
结果为:
2
9
2.2 反向查找
string s = "hello world!";
cout << s.rfind("l") << endl;//即从后往前第一次出现"l"的位置
结果为:9
通常我们可以这样来使用,当正向查找与反向查找得到的位置不相同说明子串不唯一。
2.3 查找所有子串在母串中出现的位置
//查找s 中flag 出现的所有位置。
string s("hello world!");
string flag="l";
int position=0;
int i=1;
while((position=s.find(flag,position))!=string::npos)
{
cout<<"position "<<i<<" : "<<position<<endl;
position++;
i++;
}
运行结果
position 1 : 2
position 2 : 3
position 3 : 9