比较 C 中从第 x 个字符开始的字符串 (C)

标签 c string compare

我使用以下代码对字符串数组进行排序:

char dirarr[MAX][MAX], temp[MAX];
for (i = 0; i < n; i++) {
  for (j = 0; j < n - 1; j++) {
     if (strcmp(dirarr[j], dirarr[j + 1]) > 0) {
        strcpy(temp, dirarr[j]);
        strcpy(dirarr[j], dirarr[j + 1]);
        strcpy(dirarr[j + 1], temp);
     }
  }
}

现在我遇到了以下问题,但没有找到解决方案: 我必须对这个字符串数组进行排序,但我必须从第六个字符开始比较它,而不是从每个字符串的开头开始比较。我尝试了一些方法,但没有找到有效的解决方案。 你能帮我解决这个问题吗?

谢谢阿明

最佳答案

for (i = 0; i < n; i++) {
  for (j = 0; j < n - 1; j++) {

     // Make sure that there are at least 6 characters in each string.
     if ( strlen(dirarr[j]) > 5 && strlen(dirarr[j + 1]) > 5 )
     {
        // Compare from the 6-th characters
        if (strcmp(dirarr[j]+5, dirarr[j + 1]+5) > 0) {
          strcpy(temp, dirarr[j]);
          strcpy(dirarr[j], dirarr[j + 1]);
          strcpy(dirarr[j + 1], temp);
        }
     }

     // Figure out what do when one of the strings has less than 6 characters
     else
     {
     }

  }
}

关于比较 C 中从第 x 个字符开始的字符串 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166224/

相关文章:

c++ - ReadDirectoryChangesW 问题

java - Map<Integer, String> 还是 String[]?

perl - 我可以在Perl中将参数传递给sort的compare子例程吗?

c - 如何比较两个文件的字符串?

c - Makefile,链接库

在 C 中计算斐波那契递归调用的次数

Java - 我应该为日志消息使用常量吗?

C++ 字符串数组搜索每个项目的输出

c - 在C中将格式化文件读入char数组

c++ - 就像在 python 中定义 __str__ 一样,在类上调用时如何覆盖 c++ 中的标准全局函数