C语言单词个数统计

编写一个函数 findStr(char *str,char *substr),该函数统计一个长度为 2 的子字符串在另一 个字符串中出现的次数。例如,假定输入的字符串为"asd asasdfg asd as zx67 asd mklo",子字符串为"as",函数返回值是 6。

函数 ReadWrite()实现从文件 in.dat 中读取两个字符串,并调用函数 findStr(),后把结 果输出到文件 out.dat 中。
#include <stdio.h>

#include <string.h>

#include <conio.h>

int findStr(char *str,char *substr)

{ int i,j,len1,len2,cnt=0,flag;

len1=strlen(str);

len2=strlen(substr);

for(i=0;i<len1;i++)

{ for(j=0;j<len2;j++)

if(str[i+j]==substr[j]) flag=1;

else {flag=0;break;}

if(flag==1) cnt++;

}

return cnt;

}

main()

{

char str[81], substr[3] ;

int n ;

clrscr() ;

printf(“输入原字符串:”) ;

gets(str) ;

printf(“输入子字符串:”) ;

gets(substr) ;

puts(str) ;

puts(substr) ;

=findStr(str, substr) ;

printf(“n=%d\n”, n) ;

ReadWrite() ;

}

ReadWrite()

{

char str[81], substr[3], ch;

int n, len, i = 0;

FILE *rf, *wf ;

rf = fopen(“in.dat”, “r”) ;

wf = fopen(“out.dat”, “w”) ;

while(i < 25) {

fgets(str, 80, rf) ;

fgets(substr, 10, rf) ;

len = strlen(substr) - 1 ;

ch = substr[len] ;

if(ch == ‘\n’ || ch == 0x1a) substr[len] = 0 ;

=findStr(str, substr);

fprintf(wf, “%d\n”, n) ;

i++ ;

}

fclose(rf) ;

fclose(wf) ;

}

发布了239 篇原创文章 · 获赞 3 · 访问量 3155

猜你喜欢

转载自blog.csdn.net/it_xiangqiang/article/details/105176474