If we want to know whether the string A contains the string B, we can easily know the result by using the string library function find of C++. But how many strings B are there in the string A? How do you implement the code? This problem should be think.
I'll show you here, but the method may be different. Maybe your code is much better than mine.
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
int cnt(string a,string b){
int sum=0;
int wz=0;
while(a.find(b,wz)!=string::npos){//replace "string::npos" by -1 is also right.
wz=a.find(b,wz);
sum++;
wz+=b.size();
}
return sum;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(nullptr);
string a,b;
cin>>a>>b;
cout<<cnt(a,b);
}
The next method is:
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
int cnt(string a,string b){
int lena=a.size(),lenb=b.size(),k=0;
for(int i=0;i<=lena-lenb;){
if(a[i]==b[0]&&a.substr(i,lenb)==b){
k++;
i+=lenb;
}else i++;
}
return k;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(nullptr);
string a,b;
cin>>a>>b;
cout<<cnt(a,b);
}
Thank your like!


