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

方法一:

#include <stdio.h>  
#include <ctype.h> // 引入ctype.h头文件以使用isalpha, isspace, isdigit等函数  
  
int main() {  
    char ch;  
    int letters = 0, spaces = 0, digits = 0, others = 0;  
  
    printf("请输入一行字符:\n");  
  
    // 读取字符直到遇到换行符或EOF  
    while ((ch = getchar()) != '\n' && ch != EOF) {  
        if (isalpha(ch)) { // 判断是否为英文字母  
            letters++;  
        } else if (isspace(ch)) { // 判断是否为空格  
            spaces++;  
        } else if (isdigit(ch)) { // 判断是否为数字  
            digits++;  
        } else {  
            others++; // 其他字符  
        }  
    }  
  
    // 输出统计结果  
    printf("英文字母个数: %d\n", letters);  
    printf("空格个数: %d\n", spaces);  
    printf("数字个数: %d\n", digits);  
    printf("其他字符个数: %d\n", others);  
  
    return 0;  
}

在这个程序中,我们使用了ctype.h头文件中的isalpha、isspaceisdigit函数来判断字符的类型。getchar函数用于从标准输入读取一个字符。程序使用一个while循环来读取字符,直到遇到换行符(\n)或文件结束符(EOF)。对于每个读取到的字符,程序使用条件语句来判断其类型,并相应地增加对应的计数器。最后,程序输出各种字符的个数。

方法2:

#include "stdio.h"
void main()
{
	char c;
	int letters=0,space=0,digit=0,others=0;
	printf("please input some characters\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
    others++;
    }
printf("all in all:char=%d space=%d digit=%d others=%d\n",letters,
space,digit,others);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值