题目要求
编写一个函数 int SubStrNum(char * str,char * substr) ,
它的功能是:统计子字符串substr在str中出现的次数。
如 str = “hello world hello you”; substr =“hello”,子串substr在str中出现了2次
则输出:
match times=2
如 str =“hhhhhh”;substr =“hh”;子串substr在str中出现了3次
则输出:
match times=3
注意事项
1.此题中像str =“hhhhhh”;substr =“hh"的情况算作出现了3次,而不是5次
2.输入时,str和substr之间用回车,如输入"hhhhhh”,回车,“hh"
代码实现
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int SubStrNum(char* str, char* substr);
int main()
{
char str[100];
char substr[100];
scanf_s("%[^\n]", str, 100);
getchar();
scanf_s("%[^\n]", substr, 100);
SubStrNum(str, substr);
}
int SubStrNum(char* str, char* substr)
{
int L1, L2, de = 0, times = 0;
L1 = strlen(str);
L2 = strlen(substr);
for (int i = 0;i < L1;i++)
{
if (str[i] == substr[0])
{
de = 1;
int m = i;
for (int j = 0;j < L2;m++, j++)
{
if (j == L2 - 1)break;
if (str[m + 1] == substr[j + 1])de = 1;
else { de = 0;break; }
}
}
if (de == 1) { times += 1;de = 0;i += L2 - 1; }
}
cout << "match times=" << times;
return 0;
}