书写C语言代码,设计一个子函数,分别统计任意一串字符中26个字母的个数,并在主函数中输入任意一串字符,调用此函数进行统计。
时间: 2023-06-25 21:06:14 浏览: 43
以下是代码实现:
```c
#include <stdio.h>
#include <string.h>
void countAlphabets(char *str, int *count) {
int len = strlen(str);
for(int i = 0; i < len; i++) {
if(str[i] >= 'a' && str[i] <= 'z')
count[str[i] - 'a']++;
else if(str[i] >= 'A' && str[i] <= 'Z')
count[str[i] - 'A']++;
}
}
int main() {
char str[100];
int count[26] = {0};
printf("请输入一串字符:");
fgets(str, 100, stdin);
countAlphabets(str, count);
printf("字母统计结果:\n");
for(int i = 0; i < 26; i++) {
printf("%c: %d\n", i + 'a', count[i]);
}
return 0;
}
```
首先在 countAlphabets 函数中,我们遍历了输入的字符串,如果字符是小写字母则将对应的计数器加一,如果是大写字母同理。在主函数中,我们输入了一串字符并调用 countAlphabets 函数进行统计,最后输出每个字母的计数结果。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)