输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数用c语言写出代码
时间: 2024-06-13 22:04:52 浏览: 30
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isdigit(str[i])) {
digits++;
} else if (isspace(str[i])) {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
--相关问题--:
1. 如何统计中文字符的个数?
2. 如何统计输入的字符串
相关问题
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数 用c语言写
这是两种用C语言实现输入一行字符,分别统计其中英文字母、空格、数字和其他字符个数的方法。第一种方法是常规计算,通过循环遍历输入的字符,判断每个字符的类型并计数,最后输出结果。第二种方法是定义一个函数,同样通过循环遍历输入的字符,判断每个字符的类型并计数,最后在函数中输出结果。这两种方法都可以实现相同的功能,只是实现方式不同。
代码如下:
方法一:
```c
#include <stdio.h>
int main(){
char c;
int letters=0,space=0,digit=0,other=0;
printf("请输入一行字符:\n");
while((c=getchar())!='\n'){
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
digit++;
else
other++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符数:%d",letters,space,digit,other);
return 0;
}
```
方法二:
```c
#include <stdio.h>
#include <string.h>
void count(char c[]){
int letters=0,space=0,digit=0,other=0;
int i;
for (i = 0; c[i]; i++) {
if(c[i]>='a'&&c[i]<='z'||c[i]>='A'&&c[i]<='Z')
letters++;
else if(c[i]==' ')
space++;
else if(c[i]>='0'&&c[i]<='9')
digit++;
else
other++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符数:%d",letters,space,digit,other);
}
int main(){
char c[32];
printf("请输入一行字符:\n");
gets(c);
count(c);
return 0;
}
```
用c语言的循环语句输入一行字符分别统计出其中英文字母空格数字和其他字符的个数
使用C语言的循环语句可以输入一行字符并统计其中英文字母、空格、数字和其他字符的个数。下面是一个示例代码:
```c
#include <stdio.h>
int main() {
char c;
int ch, s, d, o;
ch = 0;
s = 0;
d = 0;
o = 0;
while ((c = getchar()) != '\n') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
ch++;
else if (c == ' ')
s++;
else if (c >= '0' && c <= '9')
d++;
else
o++;
}
printf("char=%d space=%d digit=%d others=%d\n", ch, s, d, o);
return 0;
}
```
该代码使用了一个while循环来读取输入的字符,然后使用if语句来判断字符的类型并相应地增加计数器的值。最后,使用printf函数输出统计结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)