c语言实现:输入一个字符串,统计英语字母、数字字符、其它字符的个数。
时间: 2024-05-09 09:15:34 浏览: 141
以下是C语言实现,可以使用`ctype.h`头文件中的函数判断字符类型:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letter = 0, digit = 0, other = 0;
int i;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为英文字母
letter++;
} else if (isdigit(str[i])) { // 判断是否为数字字符
digit++;
} else { // 其它字符
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("其它字符个数:%d\n", other);
return 0;
}
```
以上代码中,`fgets()`函数用于从标准输入中获取字符串,`isalpha()`函数判断字符是否为英文字母,`isdigit()`函数判断字符是否为数字字符。
相关问题
用c语言编写一个代码:输入一串字符串,统计字母、数字、空格以及其他字符的个数,使用while语句
在C语言中,你可以使用while循环结合ASCII码来实现这个功能。这里是一个简单的示例,用户输入字符串,然后统计其中的字母、数字、空格和其他字符的数量:
```c
#include <stdio.h>
#include <ctype.h> // 包含处理字符类型函数
int main() {
char input[100];
int alpha_count = 0, digit_count = 0, space_count = 0, other_count = 0;
int i = 0;
while (input[i] != '\0') { // 遍历直到遇到字符串结尾
if (isalpha(input[i])) { // 判断是否为字母
alpha_count++;
} else if (isdigit(input[i])) { // 判断是否为数字
digit_count++;
} else if (isspace(input[i])) { // 判断是否为空格
space_count++;
} else { // 其他字符(如特殊字符)
other_count++;
}
i++; // 移动指针到下一个字符
}
printf("字母数量:%d\n", alpha_count);
printf("数字数量:%d\n", digit_count);
printf("空格数量:%d\n", space_count);
printf("其他字符数量:%d\n", other_count);
return 0;
}
`
在这个代码里,`isalpha()`、`isdigit()` 和 `isspace()` 分别用于检查字符是否为字母、数字和空格。如果不是这些,我们就认为它属于其他字符。
用C语言实现:输入一个字符串,统计其中数字字符的个数。(10分) 程序运行结果输出示例 请输入一个字符串: abc123def456gh 字符串中数字字符的个数为: 6
以下是用C语言实现的程序:
```c
#include <stdio.h>
int main() {
char str[100];
int count = 0;
printf("请输入一个字符串:");
scanf("%s", str);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
printf("字符串中数字字符的个数为:%d", count);
return 0;
}
```
程序的思路是,先定义一个字符串数组 `str`,通过 `scanf` 函数获取用户输入的字符串。然后使用一个循环遍历字符串中的每一个字符,如果该字符是数字字符,计数器 `count` 就加一。最后输出统计结果。
阅读全文
相关推荐
















