fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. int compare_filename(const char *a, const char *b) {
  7. int i = 0, j = 0;
  8.  
  9. while (a[i] != '\0' && b[j] != '\0') {
  10. // 如果两个字符都是数字,提取完整数字进行比较
  11. if (isdigit(a[i]) && isdigit(b[j])) {
  12. // 跳过前导零
  13. int start_i = i, start_j = j;
  14. while (a[i] == '0') i++;
  15. while (b[j] == '0') j++;
  16.  
  17. // 提取数字值
  18. long num_a = 0, num_b = 0;
  19. while (isdigit(a[i])) {
  20. num_a = num_a * 10 + (a[i] - '0');
  21. i++;
  22. }
  23. while (isdigit(b[j])) {
  24. num_b = num_b * 10 + (b[j] - '0');
  25. j++;
  26. }
  27.  
  28. // 比较数字大小
  29. if (num_a < num_b) return 1; // a的数字小,a应该排前面
  30. if (num_a > num_b) return -1; // a的数字大,a应该排后面
  31.  
  32. // 如果数字相同,但前导零不同,比较原始字符串
  33. if (i - start_i != j - start_j) {
  34. const char *pa = a + start_i;
  35. const char *pb = b + start_j;
  36. while (*pa != '\0' && *pb != '\0' && isdigit(*pa) && isdigit(*pb)) {
  37. if (*pa < *pb) return 1;
  38. if (*pa > *pb) return -1;
  39. pa++;
  40. pb++;
  41. }
  42. }
  43. }
  44. // 如果两个字符都是字母,忽略大小写比较
  45. else if (isalpha(a[i]) && isalpha(b[j])) {
  46. char char_a = tolower(a[i]);
  47. char char_b = tolower(b[j]);
  48.  
  49. if (char_a < char_b) return 1; // a的字母小,a应该排前面
  50. if (char_a > char_b) return -1; // a的字母大,a应该排后面
  51.  
  52. i++;
  53. j++;
  54. }
  55. // 其他情况,按 ASCII 值比较
  56. else {
  57. if (a[i] < b[j]) return 1; // a的字符小,a应该排前面
  58. if (a[i] > b[j]) return -1; // a的字符大,a应该排后面
  59.  
  60. i++;
  61. j++;
  62. }
  63. }
  64.  
  65. // 处理一个字符串结束的情况
  66. if (a[i] == '\0' && b[j] == '\0') return 0;
  67. if (a[i] == '\0') return 1; // a较短,a应该排前面
  68. return -1; // a较长,a应该排后面
  69. }
  70.  
  71. // 测试函数
  72. int main() {
  73. // 测试用例1
  74. printf("测试用例1:\n");
  75. printf("a = \"grade1-class5-id5-zhangsan\"\n");
  76. printf("b = \"grade01-class10-id2-list\"\n");
  77. printf("期望输出: 1\n");
  78. printf("实际输出: %d\n\n", compare_filename("grade1-class5-id5-zhangsan", "grade01-class10-id2-list"));
  79.  
  80. // 测试用例2
  81. printf("测试用例2:\n");
  82. printf("a = \"grade2-class7-id2-wangwu\"\n");
  83. printf("b = \"grade2-class7-id15-zhaoliu\"\n");
  84. printf("期望输出: 1\n");
  85. printf("实际输出: %d\n\n", compare_filename("grade2-class7-id2-wangwu", "grade2-class7-id15-zhaoliu"));
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0.01s 5260KB
stdin
Standard input is empty
stdout
测试用例1:
a = "grade1-class5-id5-zhangsan"
b = "grade01-class10-id2-list"
期望输出: 1
实际输出: -1

测试用例2:
a = "grade2-class7-id2-wangwu"
b = "grade2-class7-id15-zhaoliu"
期望输出: 1
实际输出: 1