#include <stdio.h>#include <ctype.h>void stringcount(char *s) { int upper = 0, lower = 0, space = 0, digit = 0, other = 0; while (*s) { if (isupper(*s)) upper++; else if (islower(*s)) lower++; else if (*s == ' ') space++; else if (isdigit(*s)) digit++; else other++; s++; } printf("大写字母:%d\n", upper); printf("小写字母:%d\n", lower); printf("空格:%d\n", space); printf("数字:%d\n", digit); printf("其他字符:%d\n", other);}
时间: 2024-04-26 19:23:10 浏览: 20
这段代码实现了一个函数 stringcount,它接受一个指向字符串的指针参数,然后统计这个字符串中包含的大写字母、小写字母、空格、数字和其他字符的个数,并输出统计结果。该函数使用了 C 标准库中的 isupper、islower、isdigit 函数来判断字符的类型。在 while 循环中,每遍历到一个字符,就根据其类型更新相应的计数器。最后,使用 printf 函数输出统计结果。
相关问题
本题要求实现一个函数,统计给定字符串中的大写字母、小写字母、空格、数字以及其他字符各有多少。 函数接口定义如下: void stringcount(char *s) 其中*s为要统计的字符串,统计结果可以直接输出或保存在变量中。
好的,我会根据您的要求进行回答。以下是实现该函数的代码:
```c
#include <stdio.h>
#include <ctype.h>
void stringcount(char *s) {
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
while (*s) {
if (isupper(*s))
upper++;
else if (islower(*s))
lower++;
else if (*s == ' ')
space++;
else if (isdigit(*s))
digit++;
else
other++;
s++;
}
printf("大写字母:%d\n", upper);
printf("小写字母:%d\n", lower);
printf("空格:%d\n", space);
printf("数字:%d\n", digit);
printf("其他字符:%d\n", other);
}
```
该函数中使用了ctype.h头文件中的函数,isupper、islower、isdigit分别用于判断字符是否为大写字母、小写字母、数字。函数中定义了五个变量,分别统计五种字符的数量。然后使用while循环遍历字符串中的每一个字符,根据字符的类型进行相应的计数。最后输出各种字符的数量。
调用该函数的方式如下:
```c
int main() {
char str[] = "Hello, World! 123";
stringcount(str);
return 0;
}
```
输出结果为:
```
大写字母:2
小写字母:8
空格:2
数字:3
其他字符:2
```
编写C语言程序,实现的功能是:统计一个字符串中大写字母、小写字母、数字和其他字符的个数,用指针实现,不用ctype.h头文件
好的,下面是实现代码:
```c
#include <stdio.h>
void count_chars(char *str, int *upper, int *lower, int *digit, int *other) {
while (*str) {
if (*str >= 'A' && *str <= 'Z') {
(*upper)++;
} else if (*str >= 'a' && *str <= 'z') {
(*lower)++;
} else if (*str >= '0' && *str <= '9') {
(*digit)++;
} else {
(*other)++;
}
str++;
}
}
int main() {
char str[100];
int upper = 0, lower = 0, digit = 0, other = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
count_chars(str, &upper, &lower, &digit, &other);
printf("大写字母:%d\n小写字母:%d\n数字:%d\n其他字符:%d\n", upper, lower, digit, other);
return 0;
}
```
这个程序与前一个程序类似,只是没有使用 `ctype.h` 中的函数。我们改为使用字符的 ASCII 码来判断它们的类型。大写字母的 ASCII 码范围是 65 到 90,小写字母的 ASCII 码范围是 97 到 122,数字的 ASCII 码范围是 48 到 57。其他字符的 ASCII 码不在这些范围内。
虽然这个程序没有使用 `ctype.h` 中的函数,但它也可以正确地统计字符串中各种字符的个数。