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
相关推荐
LDR00610 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
Luminous.10 天前
C语言--day30
c语言·开发语言
玖玥拾10 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
謓泽10 天前
C语言不是语法,是通往机器的地图。
c语言·开发语言
不会C语言的男孩10 天前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言
2601_9516438810 天前
C语言长文整理,关键字和数据类型
c语言·数据类型·关键字·嵌入式开发·格式化输出
m0_5474866610 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
✎ ﹏梦醒͜ღ҉繁华落℘10 天前
编程基础 --高内聚,低耦合
c语言·单片机
QK_0010 天前
C语言 static 关键字三大作用
c语言·开发语言
隔窗听雨眠10 天前
C语言函数递归从入门到精通(下):性能优化与工程实践
c语言·算法·性能优化