C语言学习-菜鸟教程C经典100例-练习79

C语言学习-菜鸟教程C经典100例-练习79

题目

字符串排序。


代码

c 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 20 //定义常量表示字符串的最大长度

// 函数声明,用于交换两个字符串
void swap(char *str1, char *str2);

int main(){
    char str1[MAX_LEN], str2[MAX_LEN], str3[MAX_LEN];

    // 提示用户输入字符串
    printf("请输入3个字符串,每个字符串以回车结束:\n");

    // 使用fgets读取输入并去除换行符
    fgets(str1, sizeof(str1), stdin);
    str1[strcspn(str1, "\n")] = '\0'; // 去除换行符

    fgets(str2, sizeof(str2), stdin);
    str2[strcspn(str2, "\n")] = '\0';  // 去除换行符

    fgets(str3, sizeof(str3), stdin);
    str3[strcspn(str3, "\n")] = '\0';  // 去除换行符

    // 对字符串进行排序
    if(strcmp(str1, str2) > 0) swap(str1, str2);
    if(strcmp(str1, str3) > 0) swap(str1, str3);
    if(strcmp(str2, str3) > 0) swap(str2, str3);

    // 输出排序后的结果
    printf("排序后的结果为:\n");
    printf("%s\n%s\n%s\n", str1, str2, str3);

    return 0;
}

// 交换两个字符串的内容
void swap(char *str1, char *str2){
    char temp[MAX_LEN];
    strcpy(temp, str1); // 将str1复制到临时字符串temp
    strcpy(str1, str2); // 将str2复制到str1
    strcpy(str2, temp); // 将temp复制到str2
}

输出结果

c 复制代码
请输入3个字符串,每个字符串以回车结束:
b
a
t
排序后的结果为:
a
b
t
相关推荐
wuyk55512 小时前
Keil工具链-第05讲-启动文件与__main到底做了什么
c语言·stm32·单片机·嵌入式硬件·物联网
Navigator_Z20 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
冻柠檬飞冰走茶1 天前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
Hhy_11071 天前
《C++深度解构06》手撕 string —— 从底层内存管理到深浅拷贝彻底吃透
c语言·开发语言·c++·学习·visual studio
曦樂~2 天前
Cpp面筋
c语言·c++
HUANGZHENXUAN1232 天前
最大子矩阵和:从 O(n⁴) 到 O(n³) 的列压缩 + Kadane
c语言·前端
§ꦿCFོ༉2 天前
嵌入式八股文—C语言入门学习(二)
c语言·学习·嵌入式·编程语言
David猪大卫2 天前
【Linux修炼】环境变量、进程地址空间
linux·c语言·经验分享·笔记·学习·ubuntu·centos
Zwawa3 天前
两根线怎么挂住一堆设备:I2C 协议原理
c语言·单片机·嵌入式
武子康3 天前
h3.c 的两个权重槽,怎样把内存压力换成 SSD 等待
c语言·人工智能·agent