C语言输入一行字符串,统计输出字符串中出现过的大写英文字母及其数量,不使用内置函数
时间: 2023-06-02 21:04:40 浏览: 63
好的,这个问题属于编程问题,我可以回答。以下是代码示例:
```c
#include <stdio.h>
int main() {
char str[100];
int count[26] = {0}; // 统计出现数量的数组,初始值为0
printf("请输入一行字符串:\n");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
count[str[i] - 'A']++; // 出现次数+1
}
}
printf("出现过的大写英文字母及其数量如下:\n");
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
printf("%c: %d\n", 'A' + i, count[i]);
}
}
return 0;
}
```
以上代码利用了一个长度为 26 的数组 count 来统计每个英文字母出现的次数。在输入字符串时,使用 fgets 函数避免出现缓冲区溢出的问题。在遍历字符串时,如果字符是大写英文字母,则更新相应的数组元素值。最后,遍历一遍 count 数组,输出不为零的元素的字母和数量即可。
希望能够帮到您!
相关问题
C语言输入一行字符串,统计输出字符串中出现过的大写英文字母及其数量
好的,这个问题属于编程问题,可以回答。下面是解决方法:
可以使用字符数组进行输入,并使用isupper函数判断字符是否为大写英文字母,然后使用数组记录每个大写英文字母出现的次数,最后输出结果。
以下是示例代码:
```
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count[26] = {0}; //用于记录每个大写英文字母出现的次数
printf("请输入一行字符串:");
fgets(str, 100, stdin); //使用fgets函数输入字符串
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
count[str[i] - 'A']++;
}
}
printf("字符串中出现过的大写英文字母及其数量为:\n");
for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c:%d\n", 'A' + i, count[i]);
}
}
return 0;
}
```
希望能够帮到你。
用c语言编写一个程序 输入一个字符串 输出其中所出现过的大写英文字母
下面是一个示例程序,可以实现输入一个字符串,然后输出其中所有出现过的大写英文字母:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count[26] = {0};
int i, len;
printf("请输入一个字符串:\n");
fgets(str, 100, 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 ", 'A' + i); // 输出字母
}
}
return 0;
}
```
上述程序中,我们定义了一个字符数组 `str`,用来存储用户输入的字符串。然后我们定义了一个整型数组 `count[26]`,用来统计每个大写字母出现的次数。变量 `i` 用来循环遍历字符串中的每个字符,变量 `len` 是字符串的长度。
在循环中,我们首先使用 `isupper` 函数判断当前字符是否是大写字母。如果是,就通过 `count` 数组统计出现次数。
最后,我们再次循环输出出现过的大写英文字母。
注意,我们使用了 `fgets` 函数来从标准输入读取字符串,而不是 `scanf` 函数。这是因为 `fgets` 可以一次读取整行字符串,而 `scanf` 只能读取一个单词,容易导致输入不完整的问题。