填空题
1. 下列给定程序中,函数fun的功能是:从s所指字符串中,找出t所指字符串的个数作为函数值返回。例如,当s所指字符串中的内容为“abcdabfab”,t所指字符串的内容为“ab”,则函数返回整数3。
请改正程序中的错误,使它能得出正确的结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<string,h>
int fun (char *s, char *t)
{
int n;char *p, *r;
n=0;
while(*s)
{
p=s;
r=t;
while (*r)
/*********found*********/
if(*r=*p){r++;p++}
else break;
/*********found*********/
if(r=='\0')
n++;
s++;
}
return n;
}
void main()
{
char s[100], t[100];int m;
system("CLS");
printf ("\nPlease enter string s:");
scanf("%s",s);
printf("\nplease enter substring t:");
scanf ("%s",t);
m=fun(s,t);
printf ("\nThe result is:m=%d \n", m);
}
【正确答案】
1、(1)if( *r== *p) {r++;p++; }
(2)if( *r=='\0')
【答案解析】[考点]
本题考查:if语句,考生需要根据题意确定if语句的判断条件;字符串结束标识,所有的字符串都要以‘\0’结尾,上机考试常考知识点,考生一定要牢记;复合赋值运算,常用于循环控制和变量的累加、累乘。
从字符串s中找出子串t的方法是:从第1个字符开始,对字符串进行遍历,若s串的当前字符等于t串的第1个字符,两个字符串的指针自动加1,继续比较下一个字符;若比较至字符串t的结尾,则跳出循环;若s串的字符与t串的字符不对应相同,则继续对s串的下一个字符进行处理。