c语言实现Java语言中contains函数

功能:

用C语言查找一个字符串中是否存在给定的字串,如果存在,则返回存在的个数。

#include "stdafx.h"
#include "stdlib.h"
#ifndef NULL
#define NULL = 0;
#endif

//function:judge how many subStrings does the original string contains
int contains(const char *oriString ,const char *subString){
 int count = 0,oriLen=0,subLen=0;
 while(oriString[oriLen++]!='\0');
 while(subString[subLen++]!='\0');
 
 if(oriLen<subLen||subLen<=0)
 {
  return 0;
 }


 //search
 for(int i = 0;i<oriLen-subLen;i++)
 {
  for(int j = 0 ;j<subLen;j++)
  {
   if(oriString[i]==subString[j])
   {    
    i++;       
   }else{
    break;
   }
  }
  
  if(subString[j]=='\0')
  {
      count++;
   }
 }
 
 return count;
}
int main(int argc, char* argv[])

 int totalPoems = NULL,line=NULL;
 int *counts = NULL;

 
 //printf("%d",contains("abcdeiab didba","ab"));
 if(argc<=2)
 {
  return 0;
 }
 
 //allocate variable to record key words count
 counts = (int *)malloc((argc-2)*sizeof(int));
 if(counts==NULL)
 {
  printf("Out of memory!\n");
  return 0;
 }
 
 for(int i = 0;i<argc-2;i++)
 {
  counts[i]=0;
  printf("%s\n",argv[i+2]);
 }

 //compute the total size
 FILE *fp_head,*fp_end;
 if((fp_head = fopen(argv[1],"r"))==NULL)
 {
  return 0;
 }

 char p[100],curC;
 //first line may be a title
 if(fscanf(fp_head,"《%s》",p))
 {
  printf("《%s\n",p);
 }
 
 while(!feof(fp_head))
 {
  curC = fgetc(fp_head);
  if(curC=='\n')
  { 
   line ++;
   fp_end = fp_head;
   char temp[100];

   fscanf(fp_head,"%s",p);
   //print title
   int count = sscanf(p,"《%s》",temp);
   if(count>0)
   {
    printf("《%s\n",temp);
    totalPoems+=count;
    count = 0;
   }

   //caculate the key word counts
   for(int i = 0;i<argc-2;i++)
   {
    count = contains(p,argv[i+2]);
    if(count>0)
    {
     counts[i]+= count;
     count = 0;
    }
   }
   
  }   
 }
 
 fclose(fp_head);
 
 //print result
 printf("\n总共:%d首\n",totalPoems);
 for(i = 0;i<argc-2;i++)
 { 
  printf("其中含关键字:%s 的个数为:%d\n",argv[i+2],counts[i]);
 }

 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值