3.编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数。函数原型为:void fun(const char *str, int* char_N, int* letter_N);
时间: 2023-12-29 21:02:24 浏览: 31
以下是实现统计数字字符个数和字母字符个数的函数:
```c++
void fun(const char *str, int* char_N, int* letter_N) {
int len = strlen(str);
*char_N = 0;
*letter_N = 0;
for (int i = 0; i < len; i++) {
if (isdigit(str[i])) {
(*char_N)++;
} else if (isalpha(str[i])) {
(*letter_N)++;
}
}
}
```
遍历字符串,判断每个字符是否为数字或字母,根据判断结果更新数字字符个数和字母字符个数。其中,isdigit()函数用于判断字符是否为数字,isalpha()函数用于判断字符是否为字母。注意,char_N和letter_N参数是指针类型,需要使用指针间接访问它们的值。
相关问题
c语言编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数
可以按照以下方式编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数:
```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` 函数。然后,我们打印出数字和字母字符的数量。
c语言编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数。函数原
本可以如下编写:
```c
#include <stdio.h>
#include <ctype.h>
void countCharacters(char *str) {
int numCount = 0;
int letterCount = 0;
while(*str) {
if(isdigit(*str)) {
numCount++;
} else if(isalpha(*str)) {
letterCount++;
}
str++;
}
printf("数字字符个数:%d\n", numCount);
printf("字母字符个数:%d\n", letterCount);
}
int main() {
char input[100];
printf("请输入一个字符串:");
scanf("%s", input);
countCharacters(input);
return 0;
}
```
这个函数接收一个字符串作为参数,然后遍历这个字符串,通过isdigit()和isalpha()函数来判断其中的数字字符和字母字符,分别累加计数。最后在主函数中调用这个函数,输出统计结果。