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
相关推荐
命运之光10 小时前
【C语言完整代码】就诊信息管理系统
java·c语言·开发语言
命运之光11 小时前
【C语言完整代码】图书管理系统:图书馆场景下的增删改查实战
c语言·开发语言
沫璃染墨13 小时前
《从零入门Linux系统篇(十五):系统工具篇·六——GDB调试器详解:从程序执行控制到高级调试技巧》
linux·运维·服务器·c语言·c++
qq_4480111614 小时前
C语言中的野指针和空指针
c语言·开发语言·单片机
en.en..16 小时前
C 语言嵌入式事件驱动状态机完整教程(枚举配套)
c语言·开发语言
Yyyyyy~17 小时前
[C语言]break和continue作业
c语言·开发语言
NoteStream17 小时前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
十月的皮皮20 小时前
STM32从零到量产开发:四路继电器工业控制模块开发 -上位机 Program.cs 应用程序入口设计说明
c语言·stm32·单片机·stm32cubemx·hal库
坚持编程的菜鸟20 小时前
模拟实现memcpy
c语言·算法·模拟实现my_memcpy
小小龙学IT21 小时前
Day 28 项目调试与优化 —— 给聊天室做一次“全面体检“
c语言·开发语言