【字符】计算子字符串个数

字符串匹配问题:输入一个字符串,计算其中包含的连续给定的子字符串的个数。

例如输入字符串“ EFABCABCABCDABCDD ” , 给定子字符串“ ABC” ,输出是 3 。

函数原型: int countsub( char *str, char *subs ) 。

参数说明: str 保存输入的字符串的首地址, subs 保存需要统计的子字符串的首地址。

返回值:包含的连续子字符串的个数。

预设代码

countsub_H20.c

view plainprint?

  1. /* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */  
  2. #include <stdio.h>  
  3.   
  4. int countsub( char *str, char *ss );  
  5.   
  6. main( )  
  7. {  
  8.     char s1[1000] = {0}, s2[100] = {0};  
  9.     gets(s1);  
  10.     gets(s2);  
  11.     printf("%d\n", countsub( s1, s2 ) );  
  12. }  
  13.   
  14. /* PRESET CODE END - NEVER TOUCH CODE ABOVE */  

#include <string.h>
int countsub( char *str, char *ss )
{
	int max=0,count=0,l=strlen(ss);char *p=str+l,temp;
	while(*(p-1))
	{
		temp=*p;*p='\0';
		if(strcmp(str,ss)) { str++;*p++=temp;count=0;}
		else
		{
			count++;if(max<count) max=count;
			str+=l;*p=temp;p+=l;
		}
	}
	return max;
}

不能用while(*p)判断结束,*p='\0'是最后一组

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值