C中的自然排序 - "包含数字和字母的字符串数组"

T.T*_*.T. 1 c sorting algorithm natural-sort

寻找一种经过验证的生产算法. 看到这个例子, 但没有在网上或书中找到其他东西.

即file_10.txt> file_2.txt

谢谢.

Nor*_*sey 8

这是一个(测试过的)比较函数来完成这项工作.它只能理解无符号整数,而不是有符号整数或浮点数:

#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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果要使用它qsort,请使用此辅助功能:

static int compare(const void *p1, const void *p2) {
  const char * const *ps1 = p1;
  const char * const *ps2 = p2;
  return strcmpbynum(*ps1, *ps2);
}
Run Code Online (Sandbox Code Playgroud)

你可以按顺序做点什么

qsort(lines, next, sizeof(lines[0]), compare);
Run Code Online (Sandbox Code Playgroud)