find()从头开始查找出现的目标字符串
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1, s2;
cin>>s1>>s2;
int a = s2.find(s1); //在字符串s2中找字符串s1,如果找到就返回-1
cout<<a;
}
注意:find()只寻找一次,若找到了就直接退出,若要进行统计字符串出现的字数,可以设置一个循环。
查找从指定位置开始的第一次出现的目标字符串:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s, ss;
cin>>s>>ss;
int a = s.find(ss, 2);
cout<<a;
}
rfind()函数
功能也是查找目标字符串,但是它是从末尾开始查找。
find_first_of() 是查找目标字符串的首字符最先出现位置
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
cin>>s1>>s2;
int ans = s1.find_first_of(s2) ; //在s1中找s2首字母第一次出现的位置,如果没有出现,就找第二个,依次类推
cout<<ans<<endl;
}
find_last_of()
是在查找的字符串中从后面往前面开始找
find_first_not_of()找到第一个不与子串匹配的位置
换句话说就是找到第一个在子串中没有的字符
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
cin>>s1>>s2;
int ans = s1.find_first_not_of(s2) ;
cout<<ans<<endl;
}
在s1中找非s2的元素,返回第一个地址,如果s2中的元素至少有一个在s1中没出现,就返回-1, 或者在s1没有找到不是s2 的元素,也返回-1