用C语言编写程序,读入一行字符(长度小于1000),将其中出现的小写字母替换为大写字母并输出。
时间: 2023-05-21 08:02:43 浏览: 111
以下是用C语言编写的程序,可以实现读入一行字符,将其中出现的小写字母替换为大写字母并输出:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[1000];
fgets(str, 1000, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (islower(str[i])) {
putchar(toupper(str[i]));
} else {
putchar(str[i]);
}
}
return 0;
}
```
这个程序使用了 `fgets` 函数来读入一行字符,然后使用 `islower` 函数判断每个字符是否为小写字母,如果是,则使用 `toupper` 函数将其转换为大写字母并输出,否则直接输出原字符。
相关问题
编写c语言程序,读入一行字符(长度小于1000),从中找出出现频率最高的字母(大小写算不同字母)出现的次数并输出。
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char str[1000];
int count[26] = {0}; // 统计每个字母出现的次数,index 0~25 分别对应 A~Z
printf("请输入一行字符串:");
fgets(str, 1000, stdin); // 读入一行字符串
// 统计每个字母出现的次数
for (int i = 0; i < strlen(str); i++)
{
if (isalpha(str[i])) // 判断是否为字母
{
count[toupper(str[i]) - 'A']++; // 统计字母出现的次数,toupper将小写字母转换为大写字母
}
}
// 找出出现频率最高的字母
int max_count = 0;
char max_char = 'A';
for (int i = 0; i < 26; i++)
{
if (count[i] > max_count)
{
max_count = count[i];
max_char = 'A' + i; // 将 index 转换为对应的字母
}
}
printf("出现频率最高的字母为 %c,出现次数为 %d\n", max_char, max_count);
return 0;
}
```
说明:
- 使用 `fgets` 函数读入一行字符串,可以避免使用 `gets` 函数可能出现的越界问题。
- 使用一个长度为 26 的数组 `count` 统计每个字母出现的次数,其中 index 0~25 分别对应 A~Z。使用 `toupper` 函数将小写字母转换为大写字母,方便统计。
- 找出出现频率最高的字母时,遍历数组 `count`,记录出现次数最多的字母和次数,最后输出即可。
用C语言编写程序,读入一行字符(长度小于1000),从中找出出现频率最高的字母(大小写算不同字母)出现的次数并输出。
可以使用一个大小为 52 的数组来记录每个字母出现的次数,其中前 26 个元素记录小写字母出现的次数,后 26 个元素记录大写字母出现的次数。遍历输入的字符串,对于每个字母,将其对应的计数器加一。最后再遍历一遍数组,找到出现次数最多的字母即可。
以下是示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[1001];
int count[52] = {0}; // 记录每个字母出现的次数
int max_count = 0; // 出现次数最多的字母的出现次数
char max_char; // 出现次数最多的字母
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 只考虑字母
int index = islower(str[i]) ? str[i] - 'a' : str[i] - 'A' + 26;
count[index]++;
if (count[index] > max_count) {
max_count = count[index];
max_char = str[i];
}
}
}
printf("出现频率最高的字母是 %c,出现了 %d 次。\n", max_char, max_count);
return 0;
}
```
注意,这个程序只考虑了 ASCII 码中的字母,如果要支持 Unicode 字符集,需要使用更复杂的方法来统计字符出现次数。