C语言:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数

#include<stdio.h>
int main()
{
char a[50];
int letter=0,blank=0,number=0,other=0,i;
gets(a);
char c;
for(i=0;i<50;i++)
{
if((c>='A'&&c<='Z')||(c>='a'&&c<='z'))
letter++;
else if(c==' ')
blank++;
else if(c>='0'&&c<='9')
number++;
else other++;
}
printf("letter=%d,blank=%d,number=%d,other=%d",letter,blank,number,other);
return 0;
}
程序有错误,怎么改

#include <stdio.h>
void main()
{
 int letter, space, digit, other;
 char ch;
 letter = space = digit = other = 0;
 while ((ch = getchar ()) != '\n')
 {
  if (ch>='a' && ch <= 'z' || ch>='A'&&ch<='Z')
   letter++;
  else if (ch>='0' && ch <='9')
   digit++;
  else if (ch == ' ')
   space++;
  else
   other++;
 }
 printf ("字母:%d\n", letter);
 printf ("空格:%d\n", space);
 printf ("数字:%d\n", digit);
 printf ("其它字符:%d\n", other);
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-12-15
你好:

你定义字符数组 char a[50] 时,意味着这个字符串最多能容纳 50 个字符,并不是说一定是 50 个字符。(实际上是 49 个字符,因为作为字符串要有一个结束标识 '\0' 的)

你可以借助 string.h 头文件里的 strlen 函数来测量字符串的长度。

程序修改如下:

#include <stdio.h>
#include <string.h>

void main(){
int i, l;
char a[50];
char c;
int letter=0, blank=0, number=0, other=0;
gets(a);
l=strlen(a); //测量字符串 a 的实际长度
for(i=0;i<l;i++){ //遍历字符串中的每一个字符
c=a[i]; //取出下标为 i 处的字符
if((c>='A' && c<='Z') || (c>='a' && c<='z')){
letter++;
}
else if(c>='0' && c<='9'){
number++;
}
else if(c==' '){
blank++;
}
else{
other++;
}
}
printf("Letter: %d, Number: %d, Blank: %d, Other: %d\n",letter,number,blank,other);
}本回答被提问者和网友采纳
第2个回答  2012-04-19
给个推荐 谢谢!
static void Main(string[] args)
{
string str = "";
int ch = 0;//用来统计字母的数量
int sp = 0;//用来统计空格的数量
int math = 0; //用来统计数字的数量
int other=0;//用来统计其它字符的数量
Console.Write("请输入一段字符:");
str=Console.ReadLine();
char[] c = str.ToCharArray();//把字符串转换成字符数组
foreach(char i in c){
if (i >= 'a' && i <= 'z' || i >= 'A' && i <= 'Z')
ch++;
else if (i >= '0' && i <= '9')
math++;
else if (i == ' ')
sp++;
else
other++;

}
Console.WriteLine("字母有"+ch+"个,空格有"+sp+"个,数字有"+math+"个,其它字符有"+other+"个.");
Console.ReadLine();
}
第3个回答  2018-10-17
#include<stdio.h>
int main()
{char c;
int letters=0,space=0,digit=0,other=0;
printf("请输入一行字符:I am a student.\n");
while((c=getchar())!='\n')
{if(c>='a'&& c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
digit++;
else
other++;}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符数:%d\n",letters,space,digit,other);
return 0;}
第4个回答  2017-12-31
main()
{
int zm=0,kg=0,sz=0,qt=0;
char c;
while( (c = getchar()) != '\n' ) //c=getchar是从键盘获取一个字符并赋值给c,\n是换行的意思

{
if( (c>='a'&&c<='z') || (c>='A'&&c<='Z') ) zm++;
else if( c>='0'&&c<='9' ) sz++;
else if( c==' ' ) kg++;
else qt++;
}
printf("字母=%d,数字=%d,空格=%d,其他=%d\n",zm,sz,kg,qt);

}
相似回答