c语言:统计字符、数字和空格的个数


#define _CRT_SECURE_NO_WARNINGS
#include 
#include
int fun(char s[])
{
	int i=0, num=0, ch=0, sp=0, ot=0;
	while (i < 81)
	{
		if (s[i] != '\0')
		{
			if (s[i] == ' ')
				sp += 1;
			else if (48 <= s[i] && s[i] <= 57)
				num += 1;
			else if ((65 <= s[i] && s[i] <= 90) || (97 <= s[i] && s[i] <= 122))
				ch += 1;
			else
				ot += 1;
		}
		if (s[i] == '\0')
			break;
		i++;
	}
	printf("char:%d,number:%d,space:%d,other:%d\n", ch, num, sp, ot);
}
int main()
{
	char s1[81];
	gets(s1);
	fun(s1);
	return 0;
}

在这里插入图片描述
这个主要是要了解ASCII表的内容,然后根据ASCII的内容判断这个字符是属于什么,然后利用循环来遍历数组来统计。
判断是不是“\0”是防止发生数组越界访问导致的other项统计错误。

相关