统计一个字符串中某个子串的出现次数

具体要求:

编写函数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;
		}
	}
}
  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨林木风11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值