C语言统计字符串数目

C语言输入一行字符,分别统计出其中的英文字母数、空格、数字和其它字符的个数
代码表示如下
#include <stdio.h>
#include <ctype.h>//字符串函数包含的头文件
void Show()
{
 int alpha = 0;//统计英文字母
 int blank = 0;//统计空格
 int digit = 0;//统计数字
 int other = 0;//统计其它
 char ch;
 while((ch=getchar()) != '$')//getchar();从键盘获取一个字符,利用符号'$'结尾,赋值优先级低于不等号
 {
  if(isalpha(ch))//字母,字母字符在EBCDIC编码中不连续
  {
   alpha++;
  }
  else if(isdigit(ch))//数字
  {
   digit++;
  }
  else if(ch == ' ')//空格
  {
   blank++;
  }
  else
  {
   other++;
  }
 }
 printf("字母=%d,数字=%d,空格=%d,其它=%d\n",alpha,digit,blank,other);
}
int main()
{
    Show();
    return 0;
}

定义了void型函数Show,在主函数中进行调用,实现程序功能。用到了if—else语句,从键盘输入字符串以$字符结尾得出运行结果。

基础解法
#include <stdio.h>
int main()
{
    char c;
    int letters=0,space=0,digit=0,other=0;
    printf("请输入一行字符:\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;
}

上面的代码未定义函数,直接在主函数中实现其功能,键盘输入字符串运行出结果。

运行结果如下
在这里插入图片描述

在这里插入图片描述

  • 15
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值