问题 问答题

编写一个函数,用该函数可以统计一个长度为3的字符串在另一个字符串中出现的次数。例如,假定输入字符串“the abcthe they have theren”,子字符串为“the”,则应输出4。
注意:部分源程序在文件PROC2.CPP中。
请勿改动主函数和其他函数中的任何内容,仅在fun()的花括号中填入编写的若干语句。
部分源程序如下:
//PROC2.CPP
#include <iostream>
using namespace std;
#define MAX 100
int fun(char *str,char *substr);
int main()
char str[MAX],substr[3];
int n;
cout<<"Please Input the source String\n";
cin>>str;
cout<<"Please Input the subString\n";
cin>>substr;
n=fun(str, substr);
cout<<"The counter is: "<<n<<end1;
return 0;

int fun(char *str,char *substr)

//******

答案

参考答案:

int fun(char *str,char *substr)

{

int n,z;

n=0;

for (z=0;str [z] !=’\0’;z++)

{

if((str[z]==substr[0])&&(str[z+A]==substr[A])&&

(str[z+B]==substr[B]))

n++;

}

return (n);

}

解析:

本题是一道简单应用题。

①本题主要考核考生对字符串指针或字符串数组的应用能力。函数fun的形参为两个字符串的首地址。

②函数fun的功能是统计一个长度为3的字符串在另一个字符串中出现的次数。

③此函数可用一个循环体和if语句来实现。在循环体中当遇到第一个字符匹配时,就用if判断此后的第2和第3个字符是否相等,若相等则计数器加1, 否则继续循环。

单项选择题
多项选择题