我在 C 中有一个字符串数组。这些字符串存储需要卸载的文件系统的路径。
For example...
mountlist[0] = "/proc"
mountlist[1] = "/dev"
mountlist[2] = "/dev/shm"
and so on...
我需要在嵌套文件系统挂载之前卸载嵌套文件系统(因此 /dev/shm
需要在 /dev
之前卸载)。我在想,最简单的方法是按长度对字符串进行排序,最长的在前。我将数组中的字符串数存储在整数 i
中。
根据目前为止我能想到的代码,假定 strnum
是我需要访问的字符串的整数,则可以使用 mountlist[ 访问这些字符串strnum]
,对应的长度存储在length[strnum]
中。
总而言之,我怎样才能按最大长度到最小长度对数组中的字符串进行排序?我不需要实际对字符串进行排序,我只需要以正确的顺序访问它们。我无法弄清楚如何编写它,但我正在考虑创建一个 int 数组的代码,其中每个字符串数组的编号以正确的顺序排列(上面的示例是 {2, 0, 1}),所以如果该数组被命名为 sort
然后 mountlist[sort[0]]
将是最长的字符串。对于这样的数组,相应的 for
循环将是:
for (int q = 0; q < i; q++) {
umount(mountlist[sort[q]]);
}
最佳答案
您可以将 qsort
与自定义比较器一起使用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *first, const void *second) {
const char **firstCast = (const char ** )first;
const char **secondCast = (const char **) second;
return strcmp(*secondCast, *firstCast);
}
int main(void) {
const char *a[3];
a[0] = "longest";
a[1] = "short";
a[2] = "medium";
qsort(a, 3, sizeof(char *), cmp);
for (int i = 0 ; i < 3; i++) {
printf("%s\n", a[i]);
}
}
关于c - 在 C 中按字符串长度对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079064/