用C语言实现:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
时间: 2023-11-25 19:08:00 浏览: 34
```c
#include <stdio.h>
int main() {
char c;
int letter = 0, space = 0, digit = 0, other = 0;
printf("请输入一行字符:\n");
while ((c = getchar()) != '\n') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
letter++;
} else if (c == ' ') {
space++;
} else if (c >= '0' && c <= '9') {
digit++;
} else {
other++;
}
}
printf("其中英文字母个数为:%d\n", letter);
printf("其中空格个数为:%d\n", space);
printf("其中数字个数为:%d\n", digit);
printf("其中其他字符个数为:%d\n", other);
return 0;
}
```
相关问题
c语言编程:输入一行字符,分别统计出其中英文字母和数字和空格和其他字符的个数。
以下是C语言的代码实现:
```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;
}
```
使用c语言编程:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
以下是使用C语言编写的统计字符类型个数的程序:
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int i, letters, digits, spaces, others;
letters = digits = spaces = 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;
}
```
该程序首先定义了一个字符数组`str`和四个整型变量`letters`、`digits`、`spaces`、`others`,分别用于统计字母、数字、空格和其他字符的个数。然后通过`fgets()`函数从标准输入中读取一行字符,并使用`for`循环遍历该字符串中的每个字符,根据字符的类型将相应的计数器加1。最后输出各个计数器的值即可。