编写函数,统计字符串中字母,数字,空格和其他字符的个数,要求在主函数中输入字符串,并输入统计的结果

如题所述

编写函数,统计字符串中字母,数字,空格和其他字符的个数,要求在主函数中输入字符串,并输入统计的结果

#include<stdio.h>

int main()

{

int count1,counta,space1,count_; //count1数字统计 ,counta字母统计,space1空格统计,count_其他字符统计

char ch;

    count1=counta=space1=count_=0;

    printf("输入字符串:");

    while((ch=getchar())!='\n')

    {

       if((ch>='0')&&(ch<='9'))

       {

           count1++;

       }

       else if((ch>='a'&&ch<='z')||ch>='A'&&ch<='Z')

       {

           counta++;

       }

       else if((ch==32))

       {

           space1++;

       }

       else

       {

           count_++;

       }

   

    }

printf("数字%d个、字母%d个、空格%d个、其他字符%d个\n",count1,counta,space1,count_);

return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-10-04
#include<stdio.h>
int
main()
{

int
i,cc,cd,ce,co;

char
str[100];

printf("输入字符串:");

gets(str);

cc=cd=ce=co=0;

for(i=0;
str[i]!='\0';
i++)

{

if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z')

{

cc++;

}

else
if(str[i]>='0'&&str[i]<='9')

{

cd++;

}

else
if(str[i]=='
')

{

ce++;

}

else

{

co++;

}

}

printf("字母、数字、空格和其他字符的个数分别为:%d、%d、%d、%d\n",cc,cd,ce,co);
}
第2个回答  2022-04-03
#include<stdio.h>
void count(char str[],int *x0,int *x1,int *x2,int *x3);
int main(void)
{
char str[100];
int x0,x1,x2,x3;//x0--数字个数;x1--字母个数;x2--空格个数;x3--其它字符个数
x0=x1=x2=x3=0;//赋初始值0,应该计数
printf("Please input str:");
gets(str);
count(str,&x0,&x1,&x2,&x3);//地址传递
printf("数字x0:%d\t 字母x1:%d\t 空格x2:%d\t 其他字符x3:%d\n",x0,x1,x2,x3);
return (0);
}
void count(char str[],int *x0,int *x1,int *x2,int *x3)//因为是地址传递,所以不需要返回值类型
{
int i;
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='0'&&str[i]<='9')
*x0+=1;
else
if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z')
*x1+=1;
else if(str[i]==' ')
*x2+=1;
else *x3+=1;
}
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网