C 语言字符串字典排序

问题描述

对分行输入的若干字符串按字典序(由小到大)进行排序并输出。

输入形式

控制台输入多行字符串,各个字符串可能含有空格。

输出形式

输出按字典序(由小到大)进行排序后内容:的字符串,每行一个,不包括输入时的行末换行符。

样例输入

'Hello world' 'I am a student' 'C program'

样例输出

'C program' 'Hello world' 'I am a student'

提示

可以使用 C 语言中的 strcmp 函数进行字符串比较,strcmp(a,b) 的返回值为:

  • 若 a>b,返回正整数
  • 若 a<b,返回负整数
  • 若 a=b,返回 0

代码示例

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

#define MAX_STR_NUM 100
#define MAX_STR_LEN 100

int main() {
    char str[MAX_STR_NUM][MAX_STR_LEN];
    int i, j, n = 0;

    // 输入字符串
    while (gets(str[n])) {
        n++;
    }

    // 冒泡排序
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            if (strcmp(str[i], str[j]) > 0) {
                char temp[MAX_STR_LEN];
                strcpy(temp, str[i]);
                strcpy(str[i], str[j]);
                strcpy(str[j], temp);
            }
        }
    }

    // 输出排序后的字符串
    for (i = 0; i < n; i++) {
        printf("%s\n", str[i]);
    }

    return 0;
}

原文地址: https://www.cveoy.top/t/topic/omcx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录