二、编程题
【知识点】字符串操作、函数、文件
【解析】仔细阅读并分析【编程要求】。【编程要求1】已对函数Replace_string指定了函数名、函数类型、形参类型和个数,并详细说明了其功能。在line指向的字符串中查找str1指向的字符子串的关键语句是当“str1[j]= =line[loc]&&str1[j]!='\0'”时继续循环查找,当 因“str1[j]!='\0'”退出循环时,则找到str1指向的字符子串,此时用str2指向的字符串替换在line中的str1字符子串,返回。【编程要求2】编写主函数主要功能要求是保存结果到数据文件、调用Replace_string函数、输入测试数据。这部分是最常规和基本的要求,必须掌握。
【参考答案】
#include
#include
int Replace_string (char line[],char str1[],char str2[])
{ int i=0,j,loc;
char temp[80];
while(i<=strlen(line)-strlen(str2))
{ j=0;loc=i;
while(str1[j]= =line[loc]&&str1[j]!='\0')
{ loc++;j++;}
if(str1[j]= ='\0')
{strcpy(temp,&line[loc]);strcpy(&line[i],str2);
i+=strlen(str2);strcpy(&line[loc],temp);
return 1;
}
else i++;
}
return 0;
}
main()
{ FILE *fp;
char string[100]="My EXAM_number is 0112404321.";
char number[11]="0112404321",num[11];
fp=fopen("myf2.out","w");
fprintf(fp,"%s\n",string);
gets(num);
Replace_string (string,number,num);
fprintf(fp,"%s\n",string);
fprintf(fp,"\n my exam number is: %s\n","0112404321");
fclose(fp); }
模拟试题]2010年9月NCRE二级C语言上机冲刺模拟