c语言 统计字符串中各个大写字母的个数 代码
时间: 2023-11-16 17:23:34 浏览: 115
下面是一个示例代码,可以统计一个字符串中各个大写字母的个数:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_STR_LEN 100
int main() {
char str[MAX_STR_LEN];
int count[26] = {0};
int len, i;
printf("请输入一个字符串:");
fgets(str, MAX_STR_LEN, stdin);
len = strlen(str);
for (i = 0; i < len; i++) {
if (isupper(str[i])) {
count[str[i] - 'A']++;
}
}
printf("字符串中各个大写字母的个数:\n");
for (i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c: %d\n", 'A' + i, count[i]);
}
}
return 0;
}
```
代码中使用了一个 `count` 数组,用于统计各个大写字母出现的次数。对于每个大写字母,将其转换成对应的数组下标,然后将对应的计数器加一。最后遍历一遍 `count` 数组,输出非零计数器的字母和对应的个数。
相关问题
c语言分别统计字符串中大写字母和小写字母的个数
这个问题可以回答。可以使用C语言中的字符处理函数,遍历字符串中的每个字符,判断其是否为大写字母或小写字母,然后分别统计个数即可。以下是示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int upper_count = 0, lower_count = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper_count++;
} else if (islower(str[i])) {
lower_count++;
}
}
printf("大写字母个数:%d\n", upper_count);
printf("小写字母个数:%d\n", lower_count);
return 0;
}
```
c语言 统计字符串中元音字母的个数
以下是一个使用C语言编写的统计字符串中元音字母个数的程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int vowels = 0;
printf("请输入一个字符串:");
gets(str);
for(int i=0; i<strlen(str); i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' ||
str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
{
vowels++;
}
}
printf("元音字母个数为:%d\n", vowels);
return 0;
}
```
程序中使用了一个`for`循环来遍历字符串中的每一个字符,如果当前字符是元音字母,就将计数器`vowels`加一。最后输出计数器的值即可。需要注意的是,这里将大写字母和小写字母都视为元音字母。