Given a string and a substring. The characters in the substring may be repeated.
The number of occurrences of the output substring.
Input description The length of
a string str and
a substring sub
str is greater than the length of sub
Output description
The number of occurrences of the output substring.
Input example 1
string = "today is nice. may nice day you have"
substring = "nice"
Output example 1
2
Input example 2
string = "abcabcabca"
substring = "abca"
Output example 2
3
question source: Niuke
Two layers of loops are used.
code show as below:
int find(const string &str, const string &sub){
int len1=str.size();
int len2=sub.size();
int cnt=0;
for(int i=0;i<len1;i++){
int j=0,k=i;
while(j<len2 && str[k++]==sub[j++]);
if(j==len2)
cnt++;
}
return cnt;
}