当前位置:网站首页>利用c语言实现对键盘输入的一串字符的各类字符的计数
利用c语言实现对键盘输入的一串字符的各类字符的计数
2022-08-02 14:03:00 【iccoke】
从键盘输入一串字符,求其中数字,空格,英文字母和其他字符的个数
基本思路:对每一字符进行判断并分别计数,按照这个思路得到第一层代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main(){
char c;
scanf("%c",&c);
int english_count = 0, blank_count = 0, number_count = 0, other_count = 0;
while (c != '\n') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
english_count++;
}
else if (c == ' ') {
blank_count++;
}
else if (c >= '0' && c <= '9') {
number_count++;
}
else {
other_count++;
}
}
printf("空格:%d,英文字母:%d,数字:%d,其他:%d\n",
blank_count,english_count,number_count,other_count);
return 0;
}
对英文字母,空格 ,数字以及其他字符进行判断并计数,最后分别得到了空格,英文字母,数字和其他的个数。以1234 abcd/***作为测试用例进行测试。
经过测试发现没有输出结果 ,经过调试发现程序进入死循环所以无法输出
原因是以scanf接收的只能是给的一串字符的第一个字符,进行如下更改
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
int main() {
char c;
scanf("%c", &c);
int english_count = 0, blank_count = 0, number_count = 0, other_count = 0;
while (c != '\n') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
english_count++;
}
else if (c == ' ') {
blank_count++;
}
else if (c >= '0' && c <= '9') {
number_count++;
}
else {
other_count++;
}
scanf("%c", &c);
}
printf("空格:%d,英文字母:%d,数字:%d,其他:%d\n", blank_count, english_count, number_count, other_count);
}
依旧使用1234 abcd/***作为测试用例
在while的最后一句加上scanf可以保证循环可以连续且完整的接收键盘输入的字符串
代码优化
在第一次完成代码的时候,发现如果未经测试,很难发现程序会进入死循环导致无法正常接收键盘输入的字符串。因此优化代码首先考虑如何可以正常的接收键盘输入的字符串,这里我们使用getchar()函数从键盘获取字符串。
scanf("%c",&c); <=> char c = getchar() 从键盘获取一个字符
printf("%c\n",c); <=> putchar(c)
同时我们对各个字符的判断条件进行优化,使用 is判断的字符类型 函数进行判断,在使用该函数时,因在头文件加上#include <ctype.h>
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include <ctype.h>
int main()
{
char c;
int english_count = 0, blank_count = 0, number_count = 0, other_count = 0;
while ((c = getchar()) != '\n') {
if (isalpha(c)) { //英文字母
english_count++;
}
else if (isblank(c)) { //空格
blank_count++;
}
else if (isdigit(c)) { //数字
number_count++;
}
else {
other_count++;
}
}
printf("空格:%d,英文字母:%d,数字:%d,其他:%d\n",
blank_count, english_count, number_count, other_count);
return 0;
}
用1234 abcd/***作为测试用例
这样就完成了从键盘接收一个字符串并计数的功能
边栏推荐
猜你喜欢
随机推荐
网络剪枝(1)
8576 顺序线性表的基本操作
ToF相机从Camera2 API中获取DEPTH16格式深度图
8576 Basic operations of sequential linear tables
C语言一级指针(补)
【c】小游戏---五子棋之井字棋雏形
【ROS】工控机的软件包不编译
第三单元 视图层
Flask contexts, blueprints and Flask-RESTful
Flask framework
YOLOv7使用云GPU训练自己的数据集
第十五单元 分页、过滤
关于密码加密的一点思路
深度学习框架pytorch快速开发与实战chapter3
[ROS](05)ROS通信 —— 节点,Nodes & Master
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第七章)
Raj delivery notes - separation 第08 speak, speaking, reading and writing
函数递归和动态内存初识
猜数字游戏,猜错10次关机(srand、rand、time)随机数生成三板斧(详细讲解!不懂问我!)
宏定义问题记录day2