gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:00:04 24 4
gpt4 key购买 nike

这是我的代码:

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com