最佳答案
这是一个(经过测试的)比较函数,可以完成这项工作。它只理解无符号整数,不理解有符号整数或 float :
#include <stdlib.h>
#include <ctype.h>
/* like strcmp but compare sequences of digits numerically */
int strcmpbynum(const char *s1, const char *s2) {
for (;;) {
if (*s2 == '\0')
return *s1 != '\0';
else if (*s1 == '\0')
return 1;
else if (!(isdigit(*s1) && isdigit(*s2))) {
if (*s1 != *s2)
return (int)*s1 - (int)*s2;
else
(++s1, ++s2);
} else {
char *lim1, *lim2;
unsigned long n1 = strtoul(s1, &lim1, 10);
unsigned long n2 = strtoul(s2, &lim2, 10);
if (n1 > n2)
return 1;
else if (n1 < n2)
return -1;
s1 = lim1;
s2 = lim2;
}
}
}
如果你想和qsort
一起使用,使用这个辅助函数:
static int compare(const void *p1, const void *p2) {
const char * const *ps1 = p1;
const char * const *ps2 = p2;
return strcmpbynum(*ps1, *ps2);
}
你可以按照以下顺序做一些事情
qsort(lines, next, sizeof(lines[0]), compare);
关于c - C 中的自然排序 - "array of strings, containing numbers and letters",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1343840/