统计子字符串出现次数

统计子字符串出现次数

题目要求

编写一个函数 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;
}

输出示例

在这里插入图片描述

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值