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
相关推荐
励志的小陈6 小时前
贪吃蛇(C语言实现,API)
c语言·开发语言
爱编码的小八嘎10 小时前
C语言完美演绎8-15
c语言
YSF2017_310 小时前
C语言16-makefile(3)——makefile的模式规则
linux·c语言·开发语言
dgaf12 小时前
谢谢 AI (打靶测试用文)
c语言·gpt·ai编程·d3d12
一行代码一行诗++13 小时前
C语言中scanf详解
c语言·开发语言
ZenosDoron13 小时前
keil软件修改字体,Asm editor,和C/C++ editor的区别
c语言·开发语言·c++
yuan1999714 小时前
C&CG(列与约束生成)算法,来解决“风光随机性”下的微网鲁棒配置问题
c语言·开发语言·算法
LeocenaY14 小时前
C语言面试题总结
c语言·开发语言·数据结构
爱吃芹菜炒肉15 小时前
Chapter 16: Power Management
服务器·c语言·网络·tcp/ip·pcie
Rabitebla16 小时前
【数据结构】动态顺序表实现详解:从原理到接口设计(面试视角)
c语言·开发语言·数据结构·c++·面试·职场和发展