编写程序,输入3个字符串,输出其中最长的字符串。C语言
时间: 2024-02-25 11:53:56 浏览: 40
下面是一个C语言的程序,输入3个字符串,输出其中最长的字符串:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char str1[MAX_LEN], str2[MAX_LEN], str3[MAX_LEN];
printf("请输入3个字符串,每个字符串长度不超过%d:\n", MAX_LEN);
scanf("%s%s%s", str1, str2, str3);
int len1 = strlen(str1), len2 = strlen(str2), len3 = strlen(str3);
if (len1 >= len2 && len1 >= len3) {
printf("最长的字符串是:%s\n", str1);
} else if (len2 >= len1 && len2 >= len3) {
printf("最长的字符串是:%s\n", str2);
} else {
printf("最长的字符串是:%s\n", str3);
}
return 0;
}
```
程序的思路是,首先定义3个字符串变量 `str1`、`str2`、`str3`,然后使用 `scanf` 函数从标准输入中读入3个字符串。接着使用 `strlen` 函数获取每个字符串的长度,并比较它们之间的大小关系,输出其中最长的字符串。
相关问题
用C语言编写程序,输入3个字符串,输出其中最长的字符串。
好的,下面是代码示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[100];
printf("请输入三个字符串:\n");
gets(str1);
gets(str2);
gets(str3);
int len1 = strlen(str1);
int len2 = strlen(str2);
int len3 = strlen(str3);
char *max_str = str1; // 假设第一个字符串最长
if (len2 > len1 && len2 > len3) {
max_str = str2;
}
if (len3 > len1 && len3 > len2) {
max_str = str3;
}
printf("最长的字符串为:%s\n", max_str);
return 0;
}
```
这段代码中,我们定义了三个字符串数组 `str1`、`str2` 和 `str3`,分别存储用户输入的三个字符串。接着,使用 `strlen` 函数获取每个字符串的长度,并使用三个变量 `len1`、`len2` 和 `len3` 分别存储这三个长度值。然后,使用一个指针 `max_str` 来记录最长的字符串,将其初始化为第一个字符串 `str1`。接着,我们使用 `if` 语句逐个比较长度,若第二个字符串或第三个字符串长度比当前最长字符串长,则更新 `max_str` 指针。最后输出 `max_str` 指针所指向的字符串即可。
用c语言编写程序,输入5个字符串,输出其中最大的字符串。
以下是用C语言实现输入5个字符串,输出其中最大的字符串的程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[5][30];
int i, max = 0;
printf("请输入5个字符串:\n");
for (i = 0; i < 5; i++)
{
scanf("%s", str[i]);
if (strlen(str[i]) > strlen(str[max]))
max = i;
}
printf("最大的字符串是:%s\n", str[max]);
return 0;
}
```
首先定义一个5行30列的字符数组,用于存储五个字符串。
然后使用for循环输入五个字符串,并比较它们的长度,找到其中最大的字符串。
最后输出最大的字符串即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)