用c语言输入一个字符串,统计26个大写字母各自出现的次数,并输出,要求利用指针完成上述功能
时间: 2024-03-19 08:46:04 浏览: 29
好的,下面是代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void countLetters(char *str, int *count) {
while (*str) {
if (isupper(*str)) {
int index = *str - 'A';
*(count + index) += 1;
}
str++;
}
}
int main() {
char str[100];
int count[26] = {0};
printf("请输入一个字符串:");
fgets(str, 100, stdin);
countLetters(str, count);
printf("大写字母出现的次数:\n");
for (int i = 0; i < 26; i++) {
printf("%c: %d\n", 'A' + i, *(count + i));
}
return 0;
}
```
代码中,`countLetters` 函数用于统计字符串中大写字母出现的次数,接收两个参数,第一个为指向字符串的指针,第二个为指向长度为 26 的数组的指针。在函数中,利用 `isupper` 函数判断字符是否为大写字母,如果是,则计算其在数组中对应的下标,并将对应的值加 1。
在 `main` 函数中,首先定义了一个长度为 100 的字符数组 `str` 和一个长度为 26 的整型数组 `count`,并初始化为 0。然后使用 `fgets` 函数从标准输入中读取字符串。
接着调用 `countLetters` 函数统计大写字母出现的次数,并将结果存储在数组 `count` 中。最后使用循环遍历数组 `count`,输出大写字母出现的次数。
注意,在输出字母时,需要将对应的 ASCII 码转换为字符。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)