c - 如何正确排序 C 中的字符串?

标签 c string sorting

这是我的代码:

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

int cmp(const void *a, const void *b) {
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

void print_array(char **array, size_t len) {
    size_t i;
    for(i=0; i<len; i++) {
        printf("%s, ", array[i]);
    }
    putchar('\n');
}

int main(int argc, char *argv[]) {

        char *strings[] = { "z1.doc", "z100.doc",  "z2.doc", "z3.doc", "z20.doc"};
        size_t strings_len = sizeof(strings) / sizeof(char *);
        print_array(strings, strings_len);
        qsort(strings, strings_len, sizeof(char *), cmp);
        print_array(strings, strings_len);

        system("PAUSE");
        return 1;
}

实际输出为

z1.doc, z100.doc, z2.doc, z20.doc, z3.doc

我希望它成为

z1.doc, z2.doc, z3.doc, z20.doc, z100.doc

哪里做错了?

最佳答案

实际输出是正确的,字符串“z100.doc”小于“z2.doc”。 strcmp 逐个字符进行比较,当它到达小于“2”的“1”时停止,因此 z100 < z2。

如果您将文件命名为 z001.doc、z002.doc、z003.doc、z020.doc、z100.doc,它将按照您想要的方式排序。

关于c - 如何正确排序 C 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1677535/

相关文章:

java - Spring Data MongoDB - 按多个字段排序不起作用

c - PlaySound() 与资源文件不工作

c - 不确定 'control may reach end of non-void function' 错误消息的含义

c - 查找二进制文件 C 中出现频率最高的字符串

java - 如果我们连接,System.out.println() 会创建一个字符串吗?

c - 获取单个字符并将其传递给 C 中的函数

Javascript 按字母顺序排序并将所有 double 移动到数组的末尾

C - 使用 mmap 时出现总线错误

c - 出现段错误 :11 in C. 为什么?

c# - 排序算法 - C#