c语言编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数
时间: 2023-12-28 22:05:02 浏览: 112
可以按照以下方式编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_char(char *str, int *num_count, int *alpha_count) {
while (*str != '\0') {
if (isdigit(*str)) {
(*num_count)++;
}
else if (isalpha(*str)) {
(*alpha_count)++;
}
str++;
}
}
int main() {
char str[100];
int num_count = 0, alpha_count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
count_char(str, &num_count, &alpha_count);
printf("Number of digits: %d\n", num_count);
printf("Number of alphabets: %d\n", alpha_count);
return 0;
}
```
在上面的代码中,我们定义了一个名为 `count_char` 的函数,它接受三个参数:一个字符指针 `str`,以及两个整数指针 `num_count` 和 `alpha_count`。该函数使用 `isdigit` 和 `isalpha` 函数来检测字符串中的数字和字母字符,并将它们的数量分别累加到 `num_count` 和 `alpha_count` 中。
在 `main` 函数中,我们首先获取用户输入的字符串,并将其传递给 `count_char` 函数。然后,我们打印出数字和字母字符的数量。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)