填空题 请补充函数proc(),该函数可以统计一个长度为n的字符串在另一个字符串中出现的次数。
例如,假定输入的字符串为:asd ascasdfg asd as as mlosd,子字符串为asd,则应输出3。
注意:部分源程序给出如下。
请勿改动函数main()和其他函数中的任何内容,仅在函数proc()的横线上填入所编写的若干表达式或语句。
试题程序:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
int proc(char *str, char *sub)
{
int n;
char *p, *r;
1;
while(*str)
{
p=str;
r=sub;
while(*r)
if( 2)
{
r++;
p++;
}
else
break;
if( 3)
n++;
str++;
}
return n;
}
void main()
{
char str[81], sub[3];
int n;
system("CLS");
printf("输入主字符串:");
gets(str);
printf("输入子字符串:");
gets(sub);
puts(str);
puts(sub);
n=proc(str, sub);
printf("n=%d/n", n);
}
【正确答案】
【答案解析】n=0 *r==*p *r=="/0"[解析] 由函数proc可知,变量n为字符串str中子字符串的个数,其初始值为0,因此,第一处填“n=0”。字符指针变量p和r分别指向字符串和子字符串,要对其指向的每一个字符进行比较,因此,第二处填“*r==*p”。每比较完一次,要检查指针r是否指向子字符串的结束位置,如果是说明字符串中包含一个子字符串,因此,第三处填“*r=="/0"”。