从键盘输入一串字符,求其中数字,空格,英文字母和其他字符的个数
基本思路:对每一字符进行判断并分别计数,按照这个思路得到第一层代码
#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/***作为测试用例
这样就完成了从键盘接收一个字符串并计数的功能