具体要求:
编写函数void count_substr(char *str,char *sub_str,。。。。。。),
统计字符串str中子串sub_str的出现次数,如在字符串"10101000101"中出现子串"101"的个数为2;主
函数完成字符串和子串的输入,调用count_substr函数得到子串出现的次数,在主函数中输出次数值。
要求:count_substr函数输出接口类型void不得修改为其他数据类型,请在省略号处填写其他需要的参数,你可以给出几种设计方案?
完整代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
void count_substr(char*str,char*del,int *length, int lengthsub,int &num);
int main()
{
cout<<"输入一段字符串,再输入一段子串,将统计它在原字符串中出现次数:"<<endl;
char *str=(char *)malloc(100*sizeof(char));
char *sub_str=(char *)malloc(100*sizeof(char));
cout<<"输入一段字符串:"<<endl;
cin.getline(str,100);
cout<<"输入要统计次数的子串:"<<endl;
cin.getline(sub_str,100);
int length=strlen(str);
int lengthsub=strlen(sub_str);
int num=0;
count_substr(str,sub_str,&length,lengthsub,num);
cout<<"出现的次数为:"<<num<<endl;
}
void count_substr(char*str,char*del,int *length, int lengthsub,int &num)
{
int judge=0;
for(int i=0;i<(*length);i++)
{
judge=0;
for(int j=0;j<lengthsub;j++)
{
if(str[i+j]==del[j])
{
judge=judge+1;
}
else
{
j=0;
break;
}
}
if(judge==lengthsub)
{
num=num+1;
}
}
}