3340 - 习题5-4 字符统计

输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数,分行输出该结果。

题目输入

一行字符,可以包含字母、数字、空格、标点等符号

题目输出

分行输出大小写英文字母、空格、数字和其他字符的个数。

如:

characters=字母个数

spaces=空格个数

numbers=数字个数

others=其他字符个数

输入/输出样例

题目输入

My input123 @%chars.

题目输出

characters=12
spaces=2
numbers=3
others=3

C语言解答

#include<stdio.h>
int main()
{	
	char ch;
	int letter=1,i,blank=0,number=0,others=0; 
	scanf("%c",&ch); 
	while((ch=getchar())!= '\n') 
	{		
		if('a'<=ch && ch<='z' || 'A'<=ch && ch<='Z') 
		{			
			letter++;	
		}		
		else if('0'<=ch&&ch<='9')	
		{		
			number++;	
		}		
		else if(ch==' ')	
		{			
			blank++;
		}		else	
		{			
			others++;	
		}	
	}	
	printf("characters=%d\n",letter);
	printf("spaces=%d\n",blank);
	printf("numbers=%d\n",number);
	printf("others=%d\n",others);
	return 0;
}

C++解答

#include<stdio.h>
#include<stdlib.h>
#include<string.h> 
int i,a[4];
char t;
int main()      
{        
   for(i=0;;i++) 
   {
   scanf("%c",&t);
   if(t=='\n')break;
   else if(t>='A'&&t<='Z') a[0]++;
        else if(t>='a'&&t<='z')a[0]++;
             else if(t==' ')a[1]++;  
                  else if(t>='0'&&t<='9')a[2]++;
                       else a[3]++;
                
   }
   
   printf("characters=%d\n",a[0]);
  printf("spaces=%d\n",a[1]);
  printf("numbers=%d\n",a[2]);
  printf("others=%d\n",a[3]);
}
时间限制 1 秒
内存限制 12 MB
讨论 统计
上一题 下一题