【问题标题】:sort string array in order "a A b B c C" in C在C中按“a A b B c C”的顺序对字符串数组进行排序
【发布时间】:2013-03-30 16:19:03
【问题描述】:

这是一个叫做 sort_list_forward 的小函数

struct customer * sort_list_forward (struct customer * liste_)
{
    struct customer *pointer1, *pointer2;
    struct customer tmp;

    if (liste_!=NULL)
    {
        pointer1 = liste_;
        while(pointer1 != NULL)
        {
            pointer2 = pointer1->next;
            while(pointer2 != NULL)
            {

                if (strcmp(pointer1->name,pointer2->name) > 0)
                {
                    strcpy(tmp.name, pointer2->name);
                    strcpy(pointer2->name, pointer1->name);
                    strcpy(pointer1->name, tmp.name);
                }
                pointer2 = pointer2->next;
            }
            pointer1 = pointer1->next;
        }
        return liste_;
    }
    else
    {
        printf("sortnames: no elements avaiable");
        return NULL;
    }
}

结构体 customer 的样子

typedef struct customer {
    char name[256];
    struct customer *next;
    struct customer *previous;
};

如果我使用这个函数,输出看起来像

Ann
Bernd
Hans
barbara
bart
berta
homer

但我想要一个看起来像

的输出
Ann
barbara
bart
berta
Bernd
homer
Hans

a A b B c C d D ...

我搜索了8个多小时,但一无所获:(

【问题讨论】:

  • 如果您使用std::stringstd::sort,这会容易得多。
  • 这是 C 还是 C++?我怀疑是 C。
  • 您可以根据比较标准轻松实现自己的strcmp 版本。使用标准strcmp作为参考,它是免费的

标签: c++ c string sorting


【解决方案1】:

通过调用strcoll,使用排序顺序比较您的字符串,而不是strcmp

【讨论】:

    【解决方案2】:

    使用strcasecmp作为排序顺序是忽略单词的大小写。

    【讨论】:

    • strcasecmp 不是 C 或 C++ 标准的一部分。这是 POSIX。
    • 如果我使用 strcasecmp,输出看起来像,Ann barbara bart Bernd berta Hans homer
    猜你喜欢
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2011-05-30
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多