英文单词排序(c语言版)

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

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

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

输入样例:
blue
red
yellow
green
purple

输出样例:
red blue green yellow purple

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

void sort_length(char (*p)[11], int n);    //使用数组指针指向二维数组 

int main()
{
    char word[21][11];						//不超过20, 不超过10,  要多开一个存放结束符 
    char str[11];
    int i, j, n;

    i = 0; n  = 0;
    while (1)
    {
        scanf("%s", str);
        if (str[0] == '#')						//不能写成str == '#'   str是字符串的首地址 
            break;
        strcpy(word[i], str);
        i++;
        n++;								//n记录字符串的个数 
    }
    sort_length(word, n);

    return 0;
}
void sort_length(char (*p)[11], int n)
{
    int i, j;
    char temp[11];

    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - 1 - i; j++)
        {
            if (strlen(p[j]) > strlen(p[j + 1]))
            {
                strcpy(temp, p[j]);
                strcpy(p[j], p[j + 1]);
                strcpy(p[j + 1], temp);
            }
        }
    }
    for (i = 0; i < n; i++)
        printf("%s ", p[i]);
}
以下是一个简单的C语言程序,用于对从键盘输入的7-11英文单词进行排序: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORDS 11 #define MAX_WORD_LENGTH 20 int main(void) { char words[MAX_WORDS][MAX_WORD_LENGTH]; char temp[MAX_WORD_LENGTH]; int i, j; // 从键盘输入单词 printf("请输入 %d 个单词,每个单词长度不得超过 %d 个字符:\n", MAX_WORDS, MAX_WORD_LENGTH - 1); for (i = 0; i < MAX_WORDS; i++) { scanf("%s", words[i]); } // 对单词进行排序 for (i = 0; i < MAX_WORDS - 1; i++) { for (j = i + 1; j < MAX_WORDS; j++) { if (strcmp(words[i], words[j]) > 0) { strcpy(temp, words[i]); strcpy(words[i], words[j]); strcpy(words[j], temp); } } } // 输出排序后的单词 printf("排序后的单词为:\n"); for (i = 0; i < MAX_WORDS; i++) { printf("%s\n", words[i]); } return 0; } ``` 该程序使用了一个二维字符数组 `words` 来存储输入单词,其中 `MAX_WORDS` 定义了单词的最大数量,`MAX_WORD_LENGTH` 定义了单词的最大长度(包括结尾的空字符)。 程序首先从键盘输入单词并存储到 `words` 数组中,然后使用冒泡排序单词进行排序,最后输出排序后的单词。注意,在比较单词大小时,使用了 `strcmp()` 函数,该函数可以比较两个字符串的大小,如果第一个字符串小于第二个字符串,则返回一个负数;如果两个字符串相等,则返回0;如果第一个字符串大于第二个字符串,则返回一个正数。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值