字符串排序

题目描述

编写一个程序,输入三个字符串,程序需对这三个字符串按字典序进行排序,并将排序后的结果依次输出。要求使用函数实现字符串的交换操作。

源代码

#include <stdio.h>
#include <stdlib.h>
#include <string.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(str2, str3) > 0) swap(str2, str3);
    if (strcmp(str1, str2) > 0) swap(str1, str2);
 
    // 输出排序后的结果
    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
}

输出结果

请输入3个字符串,每个字符串以回车结束!:
b
a
t
排序后的结果为:
a
b
t
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值