统计各类字符的个数

程序要求:

输入一行字符,统计其中的英文字符、数字字符、空格和其他字符的个数

常规方法:

#include <stdio.h>

#define N   80

int main()
{
    char str[N];
    int i,letter = 0,digit = 0,space = 0,others = 0;

    printf("Input a string:");
    gets(str);   //从输入缓冲区中读取一个字符串存储到str所指向的内存空间。
    for(i=0;str[i]!='\0';i++)
    {
        if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z')
            letter++;  //统计英文字符

        else if(str[i]>='0'&&str[i]<='9')
            digit++;    //统计数字字符

        else if(str[i]==' ')
            space++;    //统计空格
        else
            others++;   //统计其他字符
    }

    printf("英文字符:%d\n",letter);
    printf("数字字符:%d\n",digit);
    printf("空格符:%d\n",space);
    printf("其他字符:%d\n",others);

    return 0;
}

程序运行结果:

之所以会有警告,是因为编译器认为gets这个函数是不安全的。由于gets() 不检查边界。因此,当变量空间小于一行字符串 时, 使用 gets() 会造成溢出,程序出错。
在这里插入图片描述

使用字符处理函数:

#include <stdio.h>
#include <ctype.h>  //字符处理函数头文件

#define N   80

int main()
{
    char str[N];
    int i,letter = 0,digit = 0,space = 0,others = 0;
    printf("Input a string:");
    gets(str);  //从输入缓冲区中读取一个字符串存储到str所指向的内存空间。
    for(i=0;str[i]!='\0';i++)
    {
        if(isalpha(str[i]))
            letter++;  //统计英文字符

        else if(isdigit(str[i]))
            digit++;    //统计数字字符

        else if(isspace(str[i]))
            space++;    //统计空白字符(包括制表符)
        else
            others++;   //统计其他字符
    }

    printf("英文字符:%d\n",letter);
    printf("数字字符:%d\n",digit);
    printf("空格符:%d\n",space);
    printf("其他字符:%d\n",others);

    return 0;
}

程序运行结果:

在这里插入图片描述

程序比较:

两份代码大同小异,唯一不同的在于使用字符处理函数统计空白字符时是统计空格符加制表符的,而常规方法仅仅是统计空格符,制表符是由其他字符统计的。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

⁽⁽ଘ晴空万里ଓ⁾⁾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值