题解 | #统计字符串中子串出现的次数#
统计字符串中子串出现的次数
https://www.nowcoder.com/practice/9eb684f845a446f3b121472de2ea75cd
#include <cstdint>
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
int countSubstr(const string& str, const string& substr) {
if (substr.length() == 0) return 0;
int count = 0;
for (size_t offset = str.find(substr); offset != string::npos;
offset = str.find(substr, offset+1)) {
++count;
}
return count;
}
int main() {
char str[100] = { 0 };
char substr[100] = { 0 };
cin.getline(str, sizeof(str));
cin.getline(substr, sizeof(substr));
int count = 0;
// write your code here......
string str1(str);
string str2(substr);
count = countSubstr(str1,str2);
cout << count << endl;
return 0;
}
