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
相关推荐
爱读书的小胖11 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
Code_Solitude11 小时前
c语言:关于qsoet函数知识点
c语言·数据结构·算法
鸽鸽程序猿12 小时前
【项目】【在线判题系统】c端:竞赛报名
c语言·开发语言
H.莓飛12 小时前
【Linux】自主 Shell
linux·运维·服务器·c语言·开发语言·visual studio
爱读书的小胖13 小时前
Codewars:Last digit of a large number(C)解题分析
c语言·开发语言·r语言
想做小南娘,发现自己是女生喵14 小时前
第二周学习文档 Linux C 文件操作
linux·c语言·学习
Bluetooth73014 小时前
c语言变量的存储类别
c语言
lhbweilai19 小时前
分析FreeRTOS内核对象API的源码实现(四)
c语言·stm32·单片机
inrichtt1 天前
第八课时:SPI总线揭秘:四线全双工通信的奥
c语言·数据结构·stm32·单片机·嵌入式硬件
wuminyu1 天前
JMM学习总结:深入理解happens-before关系
java·linux·c语言·jvm·c++