用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;
}