用c语言计算一串字符里数字和字母的个数
时间: 2024-05-05 21:15:41 浏览: 17
```
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int num_count = 0, letter_count = 0;
printf("请输入一串字符:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
num_count++;
} else if (isalpha(str[i])) {
letter_count++;
}
}
printf("数字个数:%d\n字母个数:%d\n", num_count, letter_count);
return 0;
}
```
运行结果:
```
请输入一串字符:hello123world456
数字个数:6
字母个数:10
```
相关问题
用c语言输出一串字符,统计其中字母,数字,空格的个数
好的,你可以使用C语言的标准库函数来统计字符串中字母、数字、空格的个数。下面是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *string, int *letter_count, int *digit_count, int *space_count) {
/*
统计字符串中字母、数字、空格的个数
*/
char c;
while ((c = *string++) != '\0') {
if (isalpha(c)) {
(*letter_count)++;
} else if (isdigit(c)) {
(*digit_count)++;
} else if (isspace(c)) {
(*space_count)++;
}
}
}
int main() {
char string[] = "Hello World! 123";
int letter_count = 0, digit_count = 0, space_count = 0;
count_chars(string, &letter_count, &digit_count, &space_count);
printf("字母个数:%d,数字个数:%d,空格个数:%d\n", letter_count, digit_count, space_count);
return 0;
}
```
运行结果如下:
```
字母个数:10,数字个数:3,空格个数:2
```
在这个示例代码中,我们定义了一个 `count_chars` 函数来统计字符串中字母、数字、空格的个数。使用 `isalpha`、`isdigit`、`isspace` 函数来判断字符是否为字母、数字、空格。然后,我们在 `main` 函数中调用 `count_chars` 函数,并输出结果。
用C语言统计字符串中字母数字空格和其他字符的个数
可以使用C语言中的字符处理函数,如isdigit()、isalpha()、isspace()等来判断字符的类型,然后统计每种类型的字符出现的次数即可。具体实现如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alpha_count = 0, digit_count = 0, space_count = 0, other_count = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alpha_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else if (isspace(str[i])) {
space_count++;
} else {
other_count++;
}
}
printf("字母个数:%d\n", alpha_count);
printf("数字个数:%d\n", digit_count);
printf("空格个数:%d\n", space_count);
printf("其他字符个数:%d\n", other_count);
return 0;
}
```
这里使用了fgets()函数来读取输入的字符串,因为gets()函数已经被淘汰了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)