c语言统计字符串中各个字符的个数

目标:

输入一行字符,统计其中各种字符的个数。

具体代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define M 1024
void main() {
	char str[M];
	fgets(str, M, stdin);
	int space = 0;
	int letter = 0;
	int num = 0;
	int other = 0;
	for (int i = 0; i < (int)strlen(str); ++i) {
		if (str[i] == ' ') {
			space += 1;
		}
		else if (str[i] > 64 && str[i] < 91 || str[i]>96 && str[i] < 123)  {
			letter += 1;
		}
		else if (str[i] > 47 && str[i] < 58)  {
			num += 1;
		}
		else {
			if (str[i] != '\n') {//因为fgets()函数会在末尾自动加上\n,影响判断结果,需要判断是否为换行符
				other += 1;
			}
		}
	}
	printf(空格的个数为:%d\n, space);
	printf(英文字母的个数为:%d\n, letter);
	printf(数字的个数为:%d\n, num);
	printf(其他字符的个数为:%d\n, other);
	system(pause);
}

注意:fgets()函数会在字符串末尾(\0前)读入我们在键盘上敲的回车即换行符\n。

运行结果如下:

5704ecf534b3f2a07a729bf46dea266.png

推荐教程:c语言教程

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...