统计一行字符串中的英文字母个数、空格个数、数字个数、其他字符个数C语言
时间: 2024-05-28 09:08:36 浏览: 29
#include <stdio.h>
int main() {
char str[100];
int letter = 0, space = 0, digit = 0, other = 0;
printf("请输入字符串:");
fgets(str, 100, 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\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, alphabets, digits, spaces, others;
alphabets = digits = spaces = others = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i] != '\0'; i++) {
if(isalpha(str[i])) {
alphabets++;
} else if(isdigit(str[i])) {
digits++;
} else if(str[i] == ' ') {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", alphabets);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这段代码中使用了 `isalpha()`、`isdigit()` 等函数来判断一个字符是否为字母或数字,同时也判断了空格和其他字符。您可以将输入的字符串改成您需要统计的字符串。
C语言统计字符串中字母 数字 空格 其他字符个数
以下是C语言统计字符串中字母、数字、空格、其他字符个数的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void count(char str[]) {
int i, letter = 0, digit = 0, space = 0, other = 0;
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为字母
letter++;
} else if (isdigit(str[i])) { // 判断是否为数字
digit++;
} else if (isspace(str[i])) { // 判断是否为空格
space++;
} else { // 其他字符
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
}
int main() {
char str[100];
printf("请输入字符串:");
gets(str); // 读入字符串
count(str); // 调用count函数统计字符个数
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)