用C语言编写,统计各种字符个数

2025-10-04 00:30:13

1、打开visual C++ 6.0-文件-新建-文件-C++ Source File

用C语言编写,统计各种字符个数

用C语言编写,统计各种字符个数

2、定义变量:

#include<stdio.h>

main()

{

    char c;                                     /*定义c为字符型*/

    int letters = 0, space = 0, digit = 0, others = 0;    /*定义letters、space、digit、others、四个变量为基本整型*/

用C语言编写,统计各种字符个数

3、输入字符:

    printf("please input some characters\n");

    while ((c = getchar()) != '\n')                      /*当输入的不是回车时执行while循环体部分*/

用C语言编写,统计各种字符个数

4、判断是否是英文字母:

        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')

            letters++;                              /*当输入的是英文字母时变量letters加1*/

用C语言编写,统计各种字符个数

5、判断是否是空格:

        else

            if (c == ' ')

                space++;                            /*当输入的是空格时变量space加1*/

用C语言编写,统计各种字符个数

6、判断是否是数字:

        else

            if (c >= '0' && c <= '9')

                digit++;                            /*当输入的是数字时变量digit加1*/

用C语言编写,统计各种字符个数

7、判断是否是其它字符:

        else

            others++;                           /*当输入的即不是英文字母又不是空格或数字是变量others加1*/

用C语言编写,统计各种字符个数

8、输出结果:

    printf("char=%d space=%d digit=%d others=%d\n",letters,space,digit,others);    /*将最终统计结果输出*/

用C语言编写,统计各种字符个数

9、完整的源代码:

#include<stdio.h>

main()

{

    char c;                                     /*定义c为字符型*/

    int letters = 0, space = 0, digit = 0, others = 0;    /*定义letters、space、digit、others、四个变量为基本整型*/

    printf("please input some characters\n");

    while ((c = getchar()) != '\n')                      /*当输入的不是回车时执行while循环体部分*/

    {

        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')

            letters++;                              /*当输入的是英文字母时变量letters加1*/

        else

            if (c == ' ')

                space++;                            /*当输入的是空格时变量space加1*/

        else

            if (c >= '0' && c <= '9')

                digit++;                            /*当输入的是数字时变量digit加1*/

        else

            others++;                           /*当输入的即不是英文字母又不是空格或数字是变量others加1*/

    }

    printf("char=%d space=%d digit=%d others=%d\n",letters,space,digit,others);    /*将最终统计结果输出*/

}

用C语言编写,统计各种字符个数

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢