温馨提示×

c语言字符数组怎么排序

小亿
81
2024-08-22 23:53:27
栏目: 编程语言

要对C语言中的字符数组进行排序,可以使用标准库函数qsort()。首先需要包含头文件<stdlib.h>,然后定义一个比较函数来指定排序规则。

下面是一个示例程序,对字符数组进行排序:

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

// 比较函数,用于指定排序规则
int compare(const void *a, const void *b) {
    return *(char*)a - *(char*)b;
}

int main() {
    char arr[] = {'d', 'c', 'a', 'b', 'e'};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Before sorting: ");
    for (int i = 0; i < n; i++) {
        printf("%c ", arr[i]);
    }
    printf("\n");

    qsort(arr, n, sizeof(char), compare);

    printf("After sorting: ");
    for (int i = 0; i < n; i++) {
        printf("%c ", arr[i]);
    }
    printf("\n");

    return 0;
}

运行此程序,将输出:

Before sorting: d c a b e 
After sorting: a b c d e 

在比较函数compare()中,通过转换void*指针为char*指针,然后比较字符的大小来确定排序规则。然后调用qsort()函数对字符数组进行排序。

0