使用C语言编制一个程序,定义一个函数,返回一个字符串中的字母个数和非字母个数(只考虑英文字母、数字和标点符号),要求用指针作为参数。
时间: 2024-03-03 11:46:57 浏览: 102
好的,以下是使用指针作为参数的函数,统计字符串中字母和非字母的个数的程序:
```c
#include <stdio.h>
#include <ctype.h>
void count(char *str, int *letters, int *nonletters);
int main() {
char str[100];
int letters = 0, nonletters = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
count(str, &letters, &nonletters);
printf("字母个数:%d\n", letters);
printf("非字母个数:%d\n", nonletters);
return 0;
}
void count(char *str, int *letters, int *nonletters) {
while (*str != '\0') {
if (isalpha(*str)) {
(*letters)++;
} else if (!isspace(*str)) {
(*nonletters)++;
}
str++;
}
}
```
在 `count` 函数中,我们使用指针 `str` 遍历字符串中的每个字符,然后使用 `isalpha` 函数判断这个字符是否是字母。如果是字母,则增加 `letters` 的值;如果不是字母且不是空格,则增加 `nonletters` 的值。
在 `main` 函数中,我们定义了两个整数类型的变量 `letters` 和 `nonletters`,并使用指针作为参数调用 `count` 函数,统计字符串中字母和非字母的个数。最后输出结果。
请注意,这个程序只考虑英文字母、数字和标点符号。如果字符串中包含其他字符,它们将被视为非字母字符。
阅读全文
相关推荐















