首页 > 解决方案 > 在 C 中对字符串文字进行排序

问题描述

假设我有一个在运行时提供的字符串文字:

const char *example_message

我想在运行时对字符串文字中的字符进行排序。

我该怎么做?

我尝试将文字复制到一个数组中,但这不起作用,因为它的大小在编译时是未知的。

我无法就地编辑字符串文字,因为它们是不可变的。

有任何想法吗?

标签: csortingc-stringsstring-literals

解决方案


因为给定的字符指针是常量。所以它是不可变的。

因此,我可以动态或静态地创建一个临时字符数组并复制其中的值。qsort() c然后使用库函数对临时数组进行排序。

这是用于动态或静态创建临时字符数组的代码片段。

const char *str = "AZBCD";
int n = strlen(str);

char temp[n + 1];
strcpy(temp, str);

或者

const char *str = "AZBCD";
int n = strlen(str);


char *temp = (char*)malloc(sizeof(char) * n);
strcpy(temp, str);

这是结论性代码。

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

int compare(const void * a, const void * b) {
    int x = *( const unsigned char * )a;
    int y = *( const unsigned char * )b;
    /*
        For ascending order & descending order.
        Manipulate the below code and get your desire results.

        1) x < y
            a) if we return 1 then the string will sort descending order.
        2) x > y
            a) if we return 1 then the string will sort ascending order.

        Vice versa is also possible.
    */
    if(x > y) return 1;
    return 0;
}

int main(void)
{
    const char *str = "AZBCD";
    int n = strlen(str);

    printf("%s\n", str);

    char temp[n + 1];
    strcpy(temp, str);

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

    printf("%s\n", temp);

    return 0;
}


推荐阅读