|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编写一个函数
,统计字符串字母,数字,空格和,其他字符的个数
- #include <stdio.h>
- #define N 1024
- #include <ctype.h>
- void isgeshu(char str[])
- {
- int num = 0,kongge = 0,i = 0,alpha = 0;
- int ascii[N];
- for(i = 0;str[i] != '\n';i++)
- {
- if(str[i] >= '0'&&str[i] <= '9')
- {
- num++;
- }
- if(isspace(str[i);
- {
- kongge++;
- }
- if(isalpha(str[i]))
- {
- alpha++;
- }
-
- }
- printf("数字的个数是:%d\n",num);
- printf("空格的个数是:%d\n",kongge);
- printf("字母的个数是%d",alpha);
-
- }
- int main(void)
- {
- int i = 0;
- char str[N];
- printf("请输入一个字符串:");
- while((str[i++] = getchar()) != '\n');
-
- isgeshu(str);
-
- return 0;
- }
复制代码
空格的个数为什莫不对
如果其他字符也打印出来怎末办
本帖最后由 jackz007 于 2021-11-15 18:10 编辑
- #include <stdio.h>
- #define N 1024
- void isgeshu(char str[])
- {
- int num = 0 , kongge = 0 , i = 0 , alpha = 0 , others = 0 , d = 0 , w = 0 ;
- for(i = 0 ; str[i] ; i ++)
- {
- if(str[i] >= '0' && str[i] <= '9') num ++ ;
- else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha ++ ;
- else if(str[i] == ' ') kongge ++ ;
- else if(str[i] == ',') d ++ ;
- else if(str[i] == '?') w ++ ;
- else others ++ ;
- }
- printf(" 数字的个数是 : %d\n" , num) ;
- printf(" 字母的个数是 : %d\n" , alpha) ;
- printf(" 空格的个数是 : %d\n" , kongge) ;
- printf(" 逗号的个数是 : %d\n" , d) ;
- printf(" 问号的个数是 : %d\n" , w) ;
- printf("其他字符个数是 : %d\n" , others) ;
- }
- int main(void)
- {
- int i = 0 ;
- char str[N] ;
- printf("请输入一个字符串 : ") ;
- while((str[i++] = getchar()) != '\n') ;
- str[i - 1] = '\0' ;
- isgeshu(str) ;
- return 0 ;
- }
复制代码
编译、运行实况:
- D:\0002.Exercise\C>g++ -o x x.c
- D:\0002.Exercise\C>x
- 请输入一个字符串 : I am a chinese, and i am 21 years old !
- 数字的个数是 : 2
- 字母的个数是 : 25
- 空格的个数是 : 10
- 逗号的个数是 : 1
- 问号的个数是 : 0
- 其他字符个数是 : 1
- D:\0002.Exercise\C>
复制代码
|
|