统计其中英文字母、空格、数字和其他字符的个数C语言
时间: 2024-01-09 07:20:24 浏览: 40
以下是统计字符串中英文字母、空格、数字和其他字符个数的C语言代码:
```c
#include <stdio.h>
#include <ctype.h>
void count(char str[]) {
int letter = 0, space = 0, digit = 0, other = 0;
int i = 0;
while (str[i] != '\0') {
if (isalpha(str[i])) {
letter++;
} else if (isspace(str[i])) {
space++;
} else if (isdigit(str[i])) {
digit++;
} else {
other++;
}
i++;
}
printf("字母个数:%d\n空格个数:%d\n数字个数:%d\n其他字符个数:%d\n", letter, space, digit, other);
}
int main() {
char str[100];
printf("请输入字符串:");
gets(str);
count(str);
return 0;
}
```
相关问题
c语言输入一行字符分别统计其中英文字母 空格 数字 和其他字符的个数
好的,我知道了。以下是 c 语言统计字符的代码:
```
#include <stdio.h>
#include <ctype.h>
int main() {
char input;
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一行字符:\n");
while ((input = getchar()) != '\n') {
if (isalpha(input)) {
letters++;
} else if (isdigit(input)) {
digits++;
} else if (isspace(input)) {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
输入输出示例:
```
请输入一行字符:
Hello World 123!
字母个数:10
数字个数:3
空格个数:2
其他字符个数:1
```
输入一行字符分别统计英文字母空格数字和其他字符的个数用C语言
以下是一个简单的 C 语言程序,可以输入一行字符并统计其中英文字母、空格、数字和其他字符的个数。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alpha, space, digit, other;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
alpha = space = digit = other = 0;
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alpha++;
} else if (isspace(str[i])) {
space++;
} else if (isdigit(str[i])) {
digit++;
} else {
other++;
}
}
printf("英文字母个数:%d\n", alpha);
printf("空格个数:%d\n", space);
printf("数字个数:%d\n", digit);
printf("其他字符个数:%d\n", other);
return 0;
}
```
在程序中,我们定义了一个字符数组 `str`,用于存储输入的一行字符。然后,我们定义了四个变量 `alpha`、`space`、`digit` 和 `other`,分别表示英文字母、空格、数字和其他字符的个数,初始化为 0。
接下来,我们使用 `fgets()` 函数从标准输入中读取一行字符,并将其存储在 `str` 中。然后,我们使用一个循环来遍历这个字符串,对于每个字符,我们使用 `isalpha()`、`isspace()` 和 `isdigit()` 函数来判断它是英文字母、空格还是数字。如果不是这三种字符,则为其他字符。
最后,我们输出统计结果,即英文字母、空格、数字和其他字符的个数。
注意:上述程序中使用了 C 标准库中的 `isalpha()`、`isspace()` 和 `isdigit()` 函数,需要包含头文件 `<ctype.h>`。