输入一行字符,统计其中各种字符个数
编译环境VS2017
其中输出英文字母,数字,空格以及其他字符的个数
需要注意的是fgets()函数的使用,会在字符串末尾(\0前)读入我们在键盘上敲的回车即换行符\n
#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");
}
运行结果如下:

本文介绍了一个简单的C语言程序,该程序可以统计输入字符串中英文字母、数字、空格和其他字符的数量。通过使用fgets()函数从标准输入读取一行文本,并遍历每个字符来判断其类型。
&spm=1001.2101.3001.5002&articleId=88812945&d=1&t=3&u=f6143ccddf834b2c8792138c28f9d6f4)
9137

被折叠的 条评论
为什么被折叠?



