[PTA]实验11-1-1 英文单词排序

Spring-_-Bear 的 CSDN 博客导航

本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。

输入格式:

输入为若干英文单词,每行一个,以 # 作为输入结束标志。其中英文单词总数不超过 20 个,英文单词为长度小于 10 的仅由小写英文字母组成的字符串。

输出格式:

输出为排序后的结果,每个单词后面都额外输出一个空格。

输入样例:

blue
red
yellow
green
purple

输出样例:

red blue green yellow purple

来源:

来源:PTA | 程序设计类实验辅助教学平台
链接:https://pintia.cn/problem-sets/13/exam/problems/586

提交:

在这里插入图片描述

题解:

#include<stdio.h>
#include<string.h>

int main(void) {
    // 英文单词总数不超过 20 个,单词长度小于 10
    char words[20][10];
    int countWords = 0;

    // 输入单词
    while (scanf("%s", words[countWords]) == 1) {
        if (strcmp("#", words[countWords]) == 0) {
            break;
        }
        countWords++;
    }

    // 选择排序法,按单词长度从小到大排序
    for (int i = 0; i < countWords; i++) {
        for (int j = i + 1; j < countWords; j++) {
            // 从剩下的 countWords - i 个单词中查找,若有单词长度比当前单词短,则交换它们
            if (strlen(words[j]) < strlen(words[i])) {
                char temp[10];
                strcpy(temp, words[j]);
                strcpy(words[j], words[i]);
                strcpy(words[i], temp);
            }
        }
    }

    for (int i = 0; i < countWords; i++) {
        printf("%s ", words[i]);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春天熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值