c++ - 如何在C中按顺序对带有数字和字母的文件名进行排序?

标签 c++ c sorting

我已经使用以下代码按字母顺序对文件进行排序,它对文件进行排序,如图所示:

for(int i = 0;i < maxcnt;i++) 
{
    for(int j = i+1;j < maxcnt;j++)
    {           
        if(strcmp(Array[i],Array[j]) > 0)
        {            
            strcpy(temp,Array[i]);      
            strcpy(Array[i],Array[j]);      
            strcpy(Array[j],temp);    
        }    
    } 
}

enter image description here

但我需要按照在 Windows 资源管理器中看到的顺序对其进行排序

enter image description here

如何按这种方式排序?请帮忙

最佳答案

对于 C 答案,以下是 strcasecmp() 的替代品。此函数递归处理包含交替数字和非数字子字符串的字符串。您可以将它与 qsort() 一起使用:

int strcasecmp_withNumbers(const void *void_a, const void *void_b) {
   const char *a = void_a;
   const char *b = void_b;

   if (!a || !b) { // if one doesn't exist, other wins by default
      return a ? 1 : b ? -1 : 0;
   }
   if (isdigit(*a) && isdigit(*b)) { // if both start with numbers
      char *remainderA;
      char *remainderB;
      long valA = strtol(a, &remainderA, 10);
      long valB = strtol(b, &remainderB, 10);
      if (valA != valB)
         return valA - valB;
      // if you wish 7 == 007, comment out the next two lines
      else if (remainderB - b != remainderA - a) // equal with diff lengths
         return (remainderB - b) - (remainderA - a); // set 007 before 7
      else // if numerical parts equal, recurse
         return strcasecmp_withNumbers(remainderA, remainderB);
   }
   if (isdigit(*a) || isdigit(*b)) { // if just one is a number
      return isdigit(*a) ? -1 : 1; // numbers always come first
   }
   while (*a && *b) { // non-numeric characters
      if (isdigit(*a) || isdigit(*b))
         return strcasecmp_withNumbers(a, b); // recurse
      if (tolower(*a) != tolower(*b))
         return tolower(*a) - tolower(*b);
      a++;
      b++;
   }
   return *a ? 1 : *b ? -1 : 0;
}

注意事项:

  • Windows 需要 stricmp() 而不是 Unix 等效的 strcasecmp()
  • 如果数字真的很大,上面的代码将(显然)给出不正确的结果。
  • 此处忽略前导零。在我的领域,这是一个特性,而不是错误:我们通常希望 UAL0123 与 UAL123 匹配。但这可能是也可能不是您需要的。
  • 另见 Sort on a string that may contain a numberHow to implement a natural sort algorithm in c++? ,虽然那里的答案,或者在他们的链接中,与上面的代码相比,肯定是冗长而杂乱无章的,大约至少是四倍。

关于c++ - 如何在C中按顺序对带有数字和字母的文件名进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13856975/

相关文章:

c++ - std::min/float monoid 的标识元素

c++ - 保持两个由指针链接的排序 vector

c - OpenSSL AES 256 CBC 通过 C 中的 EVP api

c++ - 学习在 C++ 中实现链表堆栈类

c - 为什么我收到 'Incompatible pointer type' 警告?

c++ - malloc 是如何理解对齐的?

mysql - 如何对 mysql 中日期格式为 %m/%d/%Y 的列进行排序?

java - 算法 : Hybrid MergeSort and InsertionSort Execution Time

algorithm - 为什么这种排序算法有效?

c++ - 访问 C++ 变量时如何解析其内容?