2006年全国房价_2006年9月全国等级考试三级c语言上机题库(十九)

试题集锦 2023-06-14 网络整理 可可

【shitiku.jxxyjl.com--试题集锦】

题目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;

}

本文来源:https://shitiku.jxxyjl.com/shitijijin2/27175.html

Copyright @ 2011- 考试题库网 All Rights Reserved. 版权所有

免责声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。

 站长统计