简答题 C语言
题号 #2256750

编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为abcdefabcdeabceabcdef,子字符串为cd,则应当输出3。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数proc的花括号中填入所编写的若干语句。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
int proc(char*str.char*substr)
{

}
void main()
{
char str[81].substr[3];
int n:
system("CLS"):
printf("输入主字符串:");
gets(str);
printf("输入子字符串:");
gets(substr):
puts(str);
puts(substr):
n=proc(str,substr);
printf("n=%d\n",n);
}

进入在线模考

参考答案

暂无

答案解析

int proc(char*str.char*substr)
{
int i,j=0; //j表示其相同的个数
for(i=0;str[i+1]!='\0';i++)
if(str[i]==substr[0]&&str[i+1]==substr[1])
//长度为2的字符串在另一个字符串中出现的次数
j++;//把其放到J中
return j; //最后把其个数返回到主函数中
}
【解析】要计算出主字符串中包含子字符串的个数,应该检查主字符串中从第一个到最后一个字符。每出现一个计数变量加l,最后将得到的个数返回给主函数。

你可能感兴趣的试题

找试题 · 找答案 · 找资料 在线模考