用c语言编写:编写一个函数,由实参传来一个字符串,统计此字符串中字母,数字,空格和其他字符的个数

在主函数中输入字符串及输出上述结果

#include <stdio.h>
main()
{
char a[30];
void fun_char(char a[]);
printf("请输入字符串:");
gets(a);
fun_char(a);
}
void fun_char(char a[])
{
int i,letter=0,digit=0,space=0,other=0;
for(i=0;a[i]!='\0';i++)
{
if((a[i]<='z'&&a[i]>='a')||(a[i]<='Z'&&a[i]>='A'))
letter++;
else if(a[i]<='9'&&a[i]>='0')
digit++;
else if(a[i]==' ')//或者else if(a[i]==32)
space++;
else
other++;
}
printf("letter=%d;\tdigit=%d;\tspace=%d;\tother=%d\n",letter,digit,space,other);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-15
#include <ctype.h>
#include <stdio.h>

void CountChar(char* pszInput)
{
int iAlpha = 0;
int iSpace = 0;
int iNumber = 0;
int iOther = 0;
char c = 0;
if (NULL == pszInput)
{
printf ("参数错误!\n");
}

c = *pszInput;
while ('\0' != c)
{
if (isalpha(c))
{
++iAlpha;
}
else if (isspace(c))
{
++iSpace;
}
else if (c >= '0' && c <= '9')
{
++iNumber;
}
else
{
++iOther;
}
c = *(++pszInput);
}

printf ("字母个数:%d\n", iAlpha);
printf ("数字个数:%d\n", iNumber);
printf ("空格个数:%d\n", iSpace);
printf ("其他字符个数:%d\n", iOther);
}

int main()
{
CountChar("asdf4898 adff !@!#f 8erfe9aa8ser 98");
return 0;
}
第2个回答  2020-06-17
不用全局变量
#include<stdio.h>
int main()
{
void tongji(char s[]);
char a[20];
printf("请输入一行字符串:");
gets(a);
tongji(a);
return 0;
}
void tongji(char s[])
{
int d=0,x=0,k=0,z=0,q=0;
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='A'&&s[i]<='Z') d++;
else if(s[i]>='a'&&s[i]<='z') x++;
else if(s[i]==' ') k++;
else if(s[i]>='0'&&s[i]<='9') z++;
else q++;
}
printf("其中大写字母有%d个,小写字母有%d个\n空格有%d个,数字有%d个,其他字符有%d个\n",d,x,k,z,q);
}
用全局变量
#include<stdio.h>
int d=0,x=0,k=0,z=0,q=0;
void main()
{
void tongji(char [20]);
char a[20];
printf("请输入一串字符:");
gets(a);

tongji(a);

printf("其中大写字母有%d个\n小写字母有%d个\n空格有%d个\n数字有%d个\n其他字符有%d个\n",d,x,k,z,q);
}
void tongji(char s[20])
{
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='A'&&s[i]<='Z') d++;
else if(s[i]>='a'&&s[i]<='z') x++;
else if(s[i]==' ') k++;
else if(s[i]>='0'&&s[i]<='9') z++;
else q++;
}
}
第3个回答  2011-05-15
都很好,很强大,我自愧不如的了
第4个回答  2020-11-22
#include<stdio.h>
int main()
{
char a[100];
void fun_char(char a[]);
gets(a);
fun_char(a);
}
void fun_char(char a[])
{
int x=0,z=0,p=0,q=0;
int i;
for(i=0;a[i]!='\0';i++)
{
if(a[i]>='A'&&a[i]<='Z'||a[i]>='a'&&a[i]<='z') x++;
else if(a[i]>='0'&&a[i]<='9') z++;
else if(a[i]==' ') p++;
else q++;
}
printf("字母有%d\n空格有%d个\n数字有%d个\n其他字符有%d个\n",x,z,p,q);
}

相关了解……

你可能感兴趣的内容

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