c语言编写一个程序,统计字符串中英文字母、空格、数字和其他字母的个
时间: 2024-04-27 14:03:30 浏览: 13
数。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int alpha = 0, space = 0, digit = 0, other = 0;
printf("请输入字符串:");
fgets(str, 100, stdin);
for (int 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个,空格:%d个,数字:%d个,其他字符:%d个", alpha, space, digit, other);
return 0;
}
```
代码解释:
1. `isalpha()` 函数判断字符是否是英文字母。
2. `isspace()` 函数判断字符是否是空格。
3. `isdigit()` 函数判断字符是否是数字。
在 `for` 循环中,遍历字符串中的每个字符,根据字符的类型进行统计。最后输出结果。
相关问题
c语言while循环编写统计字符串中英文字母、空格、数字和其他字母个数
```c
#include <stdio.h>
int main()
{
char str[100];
int i = 0, letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入字符串:");
gets(str);
while(str[i] != '\0')
{
if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
letters++;
}
else if(str[i] == ' ')
{
spaces++;
}
else if(str[i] >= '0' && str[i] <= '9')
{
digits++;
}
else
{
others++;
}
i++;
}
printf("字母个数:%d\n空格个数:%d\n数字个数:%d\n其他字符个数:%d\n", letters, spaces, digits, others);
return 0;
}
```
C语言编写程序,输入一行字符,分别统计出其中的英文字母、空格、数字和其他字符的个数
以下是一个简单的C语言程序,用于统计输入字符串中的英文字母、空格、数字和其他字符的个数:
```c
#include <stdio.h>
int main() {
char str[100];
int letter = 0, space = 0, digit = 0, other = 0;
printf("请输入一行字符:");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letter++;
} else if (str[i] == ' ') {
space++;
} else if (str[i] >= '0' && str[i] <= '9') {
digit++;
} else {
other++;
}
}
printf("英文字母个数:%d
", letter);
printf("空格个数:%d
", space);
printf("数字个数:%d
", digit);
printf("其他字符个数:%d
", other);
return 0;
}
```
这个程序首先定义了一个字符数组`str`用于存储输入的字符串,然后通过`fgets`函数从标准输入读取一行字符。接下来,使用一个`for`循环遍历字符串中的每个字符,并根据字符的类型更新相应的计数器。最后,输出各类字符的个数。