编写函数fun,其功能是:求ss所指字符串中指定字符的个数,并返回此值。
例如,若输入字符串”123412132”,输入字符为”1”,则输出3。
注意:部分源程序已给出。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#define M 81
int fun(char*ss,char c)
int i=0;
for(;*ss!=’\0’;ss++)
if(*ss==c)
i++;/*求出ss所指字符串中指
定字符的个数*/
return 1:
void main()
char a[M],ch;
system("CLS");
printf("\n Please enter a string:");
gets(a);
printf("\nPlease enter a char:");
ch=getchar();
printf("\nThe number of the char is:%d\n",fun(a,ch));
参考答案:int fun(char*ss,char c)
{
int i=0;
for(;*ss!=’\0’;ss++)
if(*ss==c)
i++;/*求出ss所指字符串中指定字符的个数*/
return i;
}
解析: 此题考查用for循环遍历字符串和通过条件表达式*ss!=’\0’判断字符串是否结束。给字符串加上结束标识’\0’,通过for循环遍历字符串中每一个字符,在遇到结束标识前,如果遇到指定(即用户输入)字符,变量i加1,最后将变量i返回,即用户输入字符在串中出现的次数。