c语言字符串数组如何排序

   2024-11-05 6270
核心提示:c语言中可以通过使用库函数qsort()来对字符串数组进行排序。qsort()函数原型为:void qsort(void *base, size_t nmemb, size_t s

c语言中可以通过使用库函数qsort()来对字符串数组进行排序。

qsort()函数原型为:

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

其中,base为待排序数组的起始地址,nmemb为待排序数组的元素个数,size为每个元素的大小,compar为比较函数的指针。

比较函数的原型为:

int compar(const void *a, const void *b);

其中,ab为指向待比较元素的指针,比较函数应返回一个整数值:

若返回值小于0,则a应排在b之前;若返回值大于0,则a应排在b之后;若返回值等于0,则ab的相对顺序不变。

下面是一个示例代码,演示如何使用qsort()函数对字符串数组进行排序:

#include <stdio.h>#include <stdlib.h>#include <string.h>int compare(const void *a, const void *b) {    return strcmp(*(char **)a, *(char **)b);}int main() {    char *array[] = {"apple", "banana", "orange", "grape", "lemon"};    int length = sizeof(array) / sizeof(array[0]);    qsort(array, length, sizeof(array[0]), compare);    for (int i = 0; i < length; i++) {        printf("%s\n", array[i]);    }    return 0;}

输出结果为:

applebananagrapelemonorange

该示例中,字符串数组array中存储了5个字符串,通过调用qsort()函数对其进行排序,排序结果按照字母顺序排列。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号