Example: Write a function that can count the number of occurrences of a string of length 3 in another string.
例如,输入的字符串为asd asasdfg asd as zx67 asd mklo,子字符串为asd,则应输出4。
请勿改动主函数main与其它函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
代码如下:
#include<stdio.h>
#include<string.h>
#include<conio.h>
int fun(char*s,char*s1)
{
int n;
char*p,*r;
n=0;
while(*s)
{
p=s;
r=s1;
while(*r)
if(*r==*p)
{
r++;
p++;
}
else
break;
if(*r=='\0')
n++;
s++;
}
return n;
}
main()
{
char s[81],s1[4];
int n;
FILE*out;
printf("input main string:");
gets(s);
printf("input sub string:");
gets(s1);
puts(s);
puts(s1);
n=fun(s,s1);
printf("n=%d\n",n);
out=fopen("outfile.dat","w");
strcpy(s,"asd asasdfg asd as zx67 asd mklo");
strcpy(s1,"as");
fprintf(out,"%d",fun(s,s1));
fclose(out);
}
The output running window is as follows:
越努力越幸运!
加油,奥力给!!!