2006年9月全國等級考試三級c語言上機題庫(十九)

題目19(無憂id 144 單詞個數統計題)

 

編寫一個函式findstr(char *str,char *substr),該函式統計一個長度為2的子字元串在另一個字元串中出現的次數。例如,假定輸入的字元串為"asd asasdfg asd as zx67 asd mklo",子字元串為"as",函式返回值是6。

函式readwrite()實現從檔案in.dat中讀取兩個字元串,並調用函式findstr(),最後把結果輸出到檔案out.dat中。

注意:部分源程式存在檔案prog1.c中。

請勿改動主函式main()和其它函式中的任何內容,僅在函式findstr()的花括弧中填入你編寫的若干語句。

#include <stdio.h>

#include <string.h>

#include <conio.h>

 

int findstr(char *str,char *substr)

{ int n=0;

char *p , *r;

while ( *str )

{p=str;

r=substr;

while(*r)

if(*r==*p) { r++; p++; }

else break;

if(*r=='\0')

n++;

str++;

}

return n;

}

 

 

main()

{

char str[81], substr[3] ;

int n ;

 

clrscr() ;

printf("輸入原字元串:") ;

gets(str) ;

printf("輸入子字元串:") ;

gets(substr) ;

puts(str) ;

puts(substr) ;

n=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 ;

n=findstr(str, substr);

fprintf(wf, "%d\n", n) ;

i++ ;

}

fclose(rf) ;

fclose(wf) ;

}

 

解法二:

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;

}

解法三:

int findstr(char *str,char *substr)

{ int i,cnt=0;

for(i=0;i<strlen(str);i++)

if(str[i]==*substr&&str[i+1]==*(substr+1)) cnt++;

return cnt;

}

解法四:

int findstr(char *str,char *substr)

{int cnt=0;

while(*str)

if(*str==*substr&&*(str+1)==*(substr+1)) { cnt++; str++;}

else str++;

return cnt;

}