统计各类字符的个数

  • Post author:
  • Post category:其他

程序要求:

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

常规方法:

#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;
}

程序运行结果:

在这里插入图片描述

程序比较:

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


版权声明:本文为NICHUN12345原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。