题解 | #统计字符串中子串出现的次数#
统计字符串中子串出现的次数
https://www.nowcoder.com/practice/9eb684f845a446f3b121472de2ea75cd?tpId=225&tqId=2188001&ru=/exam/oj&qru=/ta/primary-grammar-cpp/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E8%25AF%25AD%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D225%26fromPut%3Dpc_kol_aaaxiu
#include <iostream>
#include <cstring>
using namespace std;
bool cmp(char* i, char* j, int len)
{
for (int a = 0; a < len-1; a++)
{
if (*(i + a) != *(j + a)) return false;
}
return true;
}
int substrrrr(char* p, char* s, int sublen)
{//p 子串
int num = 0 ;
int c = 0;
while (*s != '\0')
{
if (*s == *p)
{ //先找到头部匹配的位置
if (*(p + sublen - 1) == *(s + sublen - 1))
{//判断尾部是否也匹配
//cout << "尾部已匹配:" << *(p + sublen - 1) << endl;
if (cmp(p, s, sublen-1))
{ //内部也相等,说明此刻匹配到了一个子串
//cout << "发现一个" << endl;
num++; //如果里面也相等,子串数加一
}
}
}
s++;
}
return num;
}
int main() {
char str[100] = { 0 };
char substr[100] = { 0 };
cin.getline(str, sizeof(str));
cin.getline(substr, sizeof(substr));
int count = 0, sublen = 0;
char* f = substr;
while (*f != '\0')
{
sublen++;
f++;
}
// write your code here......
count = substrrrr( substr, str, sublen);
cout << count << endl;//
return 0;
}