c语言编写一个程序,统计字符串中英文字母、空格、数字和其他字母的个
时间: 2024-04-27 20:03:30 浏览: 136
数。
```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语言编写一个程序来统计字符串中英文字母、空格、数字以及其它字符的具体数量?
在C语言中,你可以通过遍历字符串并利用ASCII码特性来统计每个类型的字符数。下面是一个简单的示例程序:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int alpha_count = 0, space_count = 0, digit_count = 0, other_count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// 去除fgets添加的换行符
str[strlen(str) - 1] = '\0';
for (int i = 0; str[i]; i++) { // 遍历字符串
if (isalpha(str[i])) { // 检查是否为字母
alpha_count++;
} else if (isspace(str[i])) { // 检查是否为空格
space_count++;
} else if (isdigit(str[i])) { // 检查是否为数字
digit_count++;
} else { // 其他字符
other_count++;
}
}
printf("\nCharacter count:\n");
printf("Alphabets: %d\n", alpha_count);
printf("Spaces: %d\n", space_count);
printf("Digits: %d\n", digit_count);
printf("Other characters: %d\n", other_count);
return 0;
}
```
这个程序首先获取用户输入的字符串,然后逐个检查每个字符,利用`isalpha()`、`isspace()`和`isdigit()`函数判断其类别,并累加相应的计数器。
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;
}
```
阅读全文
相关推荐













