1.返回字符串s1在s中的位置,如果没有找到,则返回-1
- #include <iostream>
- #include <string.h>
- using namespace std;
- int main()
- {
- string s="what are you dong";
- string s1="are";
- int position;
- position=s.find(s1);
- if(position==-1)
- cout<<"not find"<<endl;
- else
- cout<<"position= "<<position<<endl;
- return 0;
- }
2.返回任意字符s1在s中第一次出现的位置,s1为字符,不能为字符串 'a' "a"都可以
- #include <iostream>
- #include <string.h>
- using namespace std;
- int main()
- {
- string s="hahahaha";
- string s1="a";
- int position;
- position=s.find_first_of(s1);
- cout<<position<<endl;
- return 0;
- }
3.从字符串s下标为a开始查找字符串s1,返回起始位置 s.find(s1,a); 查找不到返回-1
- #include <iostream>
- #include <string.h>
- using namespace std;
- int main()
- {
- string s="have a good time";
- string s1="good";
- int position;
- position=s.find(s1,3);
- cout<<position<<endl;
- position=s.find(s1,12);
- cout<<position<<endl;
- return 0;
- }
4.查找字符s1在s中出现的所有起始位置
- #include <iostream>
- #include <string.h>
- using namespace std;
- int main()
- {
- string s="abb abb abb";
- string s1="a"; //char s1='a';
- int position=0;
- int i=0;
- while((position=s.find_first_of(s1,position))!=string::npos)
- {
- cout<<position<<endl;
- position++;
- i++;//i为出现的总次数
- }
- cout<<"total="<<i<<endl;
- return 0;
- }
这里需要说明的是,string::npos
npos的原型应该是std::container_type::size_type,每一个容器类都会定义这个值,表示一个不存在的位,用于统一对容器查找结果的判断,如find函数,若没有找到相应的值,就会返回npos,大家只要判断find返回的值是不是等于npos,就能判断出,在该容器是不是存在该值,平时我们判断的时候,只是看find返回的值是否等于-1,若为-1则未找到,其实是因为string::pos为-1,故正确,但是放在其他容器就不一定是这样,故大家进行判断的时候最好用npos。
注意position++,因为要从当前的下个位置开始去找还有没有s1子串存在。
![](https://i-blog.csdnimg.cn/blog_migrate/1b2ad904562c9fe2f5a5c57727d72218.png)
5.查找字符串s1与s第一个不匹配的位置
- #include <iostream>
- #include <string.h>
- using namespace std;
- int main()
- {
- string s="aaabcd";
- string s1="aaafcd";
- int position;
- position=s.find_first_not_of(s1);
- cout<<position<<endl;
- return 0;
- }
6.反向查找,返回s1在s中的位置
- #include <iostream>
- #include <string.h>
- using namespace std;
- int main()
- {
- string s="aaabcd";
- string s1="abc";
- int position;
- position=s.rfind(s1);
- cout<<position<<endl;
- return 0;
- }
参考资料: