在主函数中定义一个能容纳的下100个字符的字符数组,调用一个数求该字符数组所存放字符串中2字符的个数,并在主函数中输出结果。若输入字符串“123412132”,则输出3。
如下:
#include <stdio.h>
int fun(char* str,char ch)
{
int cnt = 0;
int i=0;
while(str[i]!='\0')
{
if(str[i]== ch)
cnt++;
i++;
}
return cnt;
}
int main()
{
char buf[101]={0};
gets(buf); //读取一行字符串
printf("%d",fun(buf,'2'));
return 0;
}
定义100个大小的数组,定义一个函数进行数组值 查询
#include <stdio.h>
int fun(char *s)
{
int i=0,count=0;
while(s[i] != '\0')
{
if(s[i] == '2')
count++;
i++;
}
return count;
}
int main()
{
char s[101] = {0};
gets(s);
printf("2的数量是:%d\n",fun(s));
return 0;
}