当前位置 博文首页 > Jason's Blog:练习12—统计特定字符个数

    Jason's Blog:练习12—统计特定字符个数

    作者:[db:作者] 时间:2021-08-29 19:23

    题目

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

    解题步骤

    (1)定义变量接收输入;
    (2)定义特定变量;
    (3)循环计算;
    (4)多分支结构判断;
    (5)输出结果;

    C语言

    #include <stdio.h>
    
    int main()
    {
    	char input;									 
    	int word = 0, num = 0, blank = 0, other = 0; 
    	printf("please enter the character and press enter to confirm:");
    	for (; (input = getchar()) != '\n';) //注意括号位置
    	{
    		if ((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z'))
    			word++;
    		else if (input >= '0' && input <= '9')
    			num++;
    		else if (input == ' ')
    			blank++;
    		else
    			other++;
    	}
    	printf("word=%d,num=%d,blank=%d,other=%d\n", word, num, blank, other);
    	return 0;
    }
    

    说明

    1. C语言中没有字符串变量,因此一次只能接收一个字符并放入缓存区中;
    2. 这里我们接收用户输入的一行字符,并不知道用户输入的长度以及开始位置是什么,所以 for 循环中循环变量的声明和更新都无需设定,即从开始位置进入,结束位置输出。
    cs