解题思路:C标准中有一个一个头文件<ctype.h>,这里面定义了一批C语言字符处理函数,用于测试字符是否属于特定的字符类别,如字母字符、控制字符、数字、等等;
头文件:<ctype.h>
函数:
(1)int isalpha(int ch);
判断ch是否为字母,如果是返回非0,反之返回0;
(2)int isdigit(int ch);
判断ch是否为数字,如果是返回非0,反之返回0;
(3)int islower(int ch);
判断ch是否为小写字母,如果是返回非0,反之返回0;
(4)int isupper(int ch);
判断ch是否为大写字母,如果是返回非0,反之返回0;
……
等等很多处理字符的函数,大家有兴趣可以去看看博客。
注意事项:
参考代码:
#include <stdio.h> #include <ctype.h> int main() { int letter = 0,number = 0,blank = 0,others = 0,c; //分别为字母、数字、空格、其他 while((c = getchar()) != '\n'){ if(isalpha(c)) //判断是否为字母 letter++; else if(isdigit(c)) //判断是都为数字 number++; else if(c == ' ') //判断是否为空格 blank++; else //其他 others++; } printf("%d %d %d %d\n",letter,number,blank,others); return 0; }
0.0分
122 人评分
#include <stdio.h> int main() { int i,y=0,s=0,k=0,q=0; char str[200]; scanf("%s",str); for(i=0;str[i]!='\0';i++) { if(str[i]>='A'&&str[i]<='Z'||str[i]>='a'&&str[i]<='z'){ y++; } else if(str[i]>='0'&&str[i]<='9') { s++; } else if(str[i]==' ') { k++; } else q++; } printf("%d %d %d %d\n",y,s,k,q); return 0; } 为什么空格后输出不了,求大佬解析下
#include<stdio.h> int main() { int a,b,e,d,i; a=0; b=0; e=0; d=0; i=0; char c[200]; scanf("%s",c); while(c[i]!='\0'){ if(c[i]>='a'&&c[i]<='z'||c[i]>='A'&&c[i]<='Z'){ a++; } else if(c[i]>='0'&&c[i]<='9'){ e++; } else if(c[i]==32){ b++; } else{ d++; } i++; } printf("%d %d %d %d",a,b,e,d); return 0; } 求教,为什么我输入一段字符串(含空格),程序只统计我空格之前的的 例 输入 445Aa,c; 54a 输出 3 3 0 2 空格之后得就没得了。 该怎么改。
#include<stdio.h> #include<ctype.h> main(){ char c; int alpha=0; int digit=0; int blank=0; int others=0; while((c=getchar())!='\n'){ if(isalpha(c)){ alpha++; }else if(isdigit(c)){ digit++; }else if(c==' '){ blank++; }else{ others++; } } printf("%d %d %d %d",alpha,digit,blank,others); return 0; } 求解,为啥我按照题解的方法写出的代码提交后显示编译错误
int main(void) { int english,integer,space,others=0; char str[200]; int i; i=0; while((str[i]=getchar())!='\n'){ i++; } str[i]='\0'; for(i=0;str[i]!='\0';i++){ if(str[i]>='0' && str[i]<='9'){ integer++; }else if((str[i]>='A' && str[i]<='Z') || (str[i]>='a' && str[i]<='z')){ english++; }else if(str[i]==32){ space++; }else{ others++; } } printf("%d %d %d %d\n",english,integer,space,others); return 0; } 帮我看看哪里错了,例子运行数字有17个
下面这样写为什么到了输入空格就不能统计了呢?大佬们求解!!! #include<stdio.h> int main() { char s[200]; int a=0,b=0,c=0,d=0; scanf("%s",s); for(int i=0;s[i]!='\0';i++) { if(s[i]>='A'&&s[i]<='Z'||s[i]>='a'&&s[i]<='z'){ a++; } else if(s[i]>='0'&&s[i]<='9'){ b++; } else if(s[i]==' '){ c++; } else d++; } printf("%d %d %d %d",a,b,c,d); return 0; }
c为什么设定为int型,c不是一串字符吗?
咖啡 2021-06-01 17:28:35 |
一个一个读入每一个字符,单个字符在计算机内部是整数形式,即对应ACSLL码
简单的a+b (C语言代码)浏览:681 |
C语言训练-求1+2!+3!+...+N!的和 (C语言代码)浏览:779 |
【偶数求和】 (C语言代码)浏览:556 |
C语言程序设计教程(第三版)课后习题6.3 (C语言代码)from DQM浏览:652 |
Cylinder (C语言描述+详细分析)浏览:3255 |
简单的a+b (C语言代码)浏览:543 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:398 |
模拟计算器 (C语言代码)浏览:2292 |
C语言程序设计教程(第三版)课后习题6.3 (C语言代码)浏览:467 |
C语言程序设计教程(第三版)课后习题6.10 (C语言代码)浏览:505 |
沐杉 2022-03-20 13:44:39 |
每次只判断了一个字符 使用while循环才把整个字符串判断完