c语言:输入一行字符,分别统计出其中英文字母,空格,数字和其它字符的个数
#define N 100
int main()
{
char a[N];
int i,m=0,n=0,b=0,c=0;
printf("Input a string:");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>='a'&&a[i]<='z'||a[i]>='A'&&a[i]<='Z')
m++;
else if(a[i]>='0'&&a[i]<='9')
n++;
else if(a[i]==' ')
b++;
else
c++;
}
printf("英文字母:%d\n",m);
printf("数字字符:%d\n",n);
printf("空格:%d\n",b);
printf("其他字符:%d\n",c);
return 0;
}
2017-09-10
即学了编程又学了英语(没学好……),岂不美哉?
(printf()函数能用那种方式是因版本的关系)
本程序的优点:不受到字符串长度的限制,运行效率高
#include <stdio.h>
int main (void)
{
//Program fuction introduce
printf ("Character statistics.\n");
//Data
char ch;
int letnum = 0; //The number of leters
int spanum = 0; //The number of space
int dignum = 0; //The number of digits
int resnum = 0; //The number of other characters
//Data input
printf ("\nPlease input a charactor string.\n");
scanf ("%c", &ch);
//Data processing
while (ch != 10)
{
if (64 < ch && ch <91 || 96 < ch && ch < 113)
++letnum;
else if (ch == 32)
++spanum;
else if (47 < ch && ch < 58)
++dignum;
else
++resnum;
scanf ("%c", &ch);
}
++resnum; //Attention! Because of the newline (ASCII: 10)!
//Data output
printf ("\nThe results of data processing are as fellows.\n");
printf ("The number of letters:%8d\n"
"The number of space: %8d\n"
"The number of digits: %8d\n"
"The number of others:%8d\n",
letnum, spanum, dignum, resnum);
//The end
printf ("\nThank you for your using!");
return 0;
}
#define N 100
int main()
{
char a[N];
int i,m=0,n=0,b=0,c=0;
char *p;
printf("Input a string:");
gets(a);
p=a;
for(i=0;p[0]!='\0';i++,p++)
{
if(p[0]>='a'&&p[0]<='z'||p[0]>='A'&&p[0]<='Z')
m++;
else if(p[0]>='0'&&p[0]<='9')
n++;
else if(p[0]==' ')
b++;
else
c++;
}
printf("英文字母:%d\n",m);
printf("数字字符:%d\n",n);
printf("空格:%d\n",b);
printf("其他字符:%d\n",c);
return 0;
}
C语言经典例子之统计英文、字母、空格及数字个数