gpt4 book ai didi

c - 在 C 中,按字符串长度对字符串数组进行排序

转载 作者:太空狗 更新时间:2023-10-29 16:01:34 25 4
gpt4 key购买 nike

所以我将字符串输入到数组mydata[10][81]

while ((ct<=10) && gets(mydata[ct]) != NULL && (mydata[ct++][0] != '\0'))

然后我使用 for 循环创建第二个指针数组

for (i=0;i<11;i++){
ptstr[i] = mydata[i];
}

这是我卡住的地方我知道我需要以某种方式使用 strlen,但我什至无法想象如何获取指针的长度,然后根据长度的第三个附加值重新为该指针分配一个新位置

希望这是有道理的,我不知道如何去做或解释它,我只是尝试使用数组位置按长度对字符串进行排序(而不是使用 qsort 之类的东西)

我做了一些更多的工作并想出了这个:知道为什么它不起作用吗?

void orderLength(char *ptstr[], int num){
int temp;
char *tempptr;
int lengthArray[10];
int length = num;
int step, i, j, u;
for (i=0; i<num;i++){
lengthArray[i] = strlen(ptstr[i]);
}
for (step=0; step < length; step++){
for(j = step+1; j < step; j++){
if (lengthArray[j] < lengthArray[step]){
temp = lengthArray[j];
lengthArray[j] = lengthArray[step];
lengthArray[step] =temp;
tempptr=ptstr[j];
ptstr[j]=ptstr[step];

}
}
}
for (u=0; u<num; u++){
printf("%s \n", ptstr[u]);
}
}

最佳答案

正如 Deduplicator 的评论中所建议的那样,您可以使用 stdlib.h 中定义的 qsort

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ROWS 4
#define MAXLEN 20

int compare (const void * a, const void * b) {
size_t fa = strlen((const char *)a);
size_t fb = strlen((const char *)b);
return (fa > fb) - (fa < fb);
}

int main(int argc, const char * argv[]) {
char arr[ROWS][MAXLEN] = {
"abcd",
"ab",
"abcdefgh",
"abc"
};
qsort(arr, ROWS, MAXLEN, compare);
return 0;
}

您可以在实际中看到它 over here .

关于c - 在 C 中,按字符串长度对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27002906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com