我使用以下代码对字符串数组进行排序:
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/