(1)编写函数void count(char *str,int *a)统计字符串str中大写字母、小写字母、空格、数字以及其他字符的个数,统计的结果保存到数组a中。在main函数中调用该函数。
时间: 2023-05-03 13:01:50 浏览: 64
这个问题是要求我们写一个函数 void count(char *str, int *a),用来统计字符串 str 中大写字母、小写字母、空格、数字以及其他字符的个数,并将结果存储到整型数组 a 中。在主函数中调用该函数。
相关问题
编写函数void count(char *str,int *a)统计字符串str中大写字母、小写字母、空格、数字以及其他字符的个数,统计的结果保存到数组a中。在main函数中调用该函数。
题目要求编写一个函数,函数名为count,参数为一个指向字符数组的指针和一个指向整型数组的指针。函数的作用是统计字符串中大写字母、小写字母、空格、数字以及其他字符的个数,并将统计结果保存到整型数组中。在主函数中调用该函数。
函数的实现可以采用循环遍历字符串的方式,对每个字符进行判断,根据字符的ASCII码值来判断其属于哪一类字符,然后将对应的计数器加1。最后将计数器的值存入整型数组中即可。
函数的代码如下:
void count(char *str, int *a)
{
int i;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
a[0]++;
else if (str[i] >= 'a' && str[i] <= 'z')
a[1]++;
else if (str[i] == ' ')
a[2]++;
else if (str[i] >= '0' && str[i] <= '9')
a[3]++;
else
a[4]++;
}
}
在主函数中调用该函数的代码如下:
int main()
{
char str[100];
int a[5] = {0};
printf("请输入字符串:");
gets(str);
count(str, a);
printf("大写字母:%d\n", a[0]);
printf("小写字母:%d\n", a[1]);
printf("空格:%d\n", a[2]);
printf("数字:%d\n", a[3]);
printf("其他字符:%d\n", a[4]);
return 0;
}
本题要求实现一个函数,统计给定字符串中的大写字母、小写字母、空格、数字以及其他字符各有多少。 函数接口定义如下: 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
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)