c语言字符串升序排列怎么实现

803
2024/5/3 18:00:12
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,可以使用标准库函数qsort来对字符串数组进行升序排列。下面是一个示例代码:

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

int compare(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int main() {
    char *strings[] = {"hello", "world", "apple", "orange", "banana"};

    int n = sizeof(strings) / sizeof(strings[0]);
    qsort(strings, n, sizeof(char *), compare);

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

    return 0;
}

在上面的代码中,我们首先定义了一个字符串数组strings,然后定义了一个比较函数compare,用来比较两个字符串的大小关系。最后,我们调用qsort函数对字符串数组进行排序,并输出排序后的结果。

运行上面的代码,将会输出:apple banana hello orange world,即字符串数组按照字典序升序排列的结果。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言怎么实现输入年份判断闰年