在C中,按字符串长度排序字符串数组

所以我将字符串输入到数组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  #include  #include  #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] = { "watfi", "wh", "barified", "foo" }; qsort(arr, ROWS, MAXLEN, compare); return 0; } 

为了避免在相同的字符串上调用多次strlen(),可以使用列出的结构链,如下所示:

 #include  #include  typedef struct t_elem { char data[81]; int length; t_elem *next; }; int main(int ac, char **av) { t_elem *head; t_elem *recent; t_elem *current; while (/* string have to be sorted */) { if (head == NULL) { head = (t_elem *)malloc(sizeof(t_elem)); head->data = //readTheFirstString(); head->length = strlen(head->data); head->next = NULL; } else { recent = (t_elem *)malloc(sizeof(t_elem)); recent->data = //readTheNextString(); recent->length = strlen(recent->data); recent->next = NULL; if (recent->length < head->length) { recent->next = head; head = recent; } else { current = head; while (current->next && current->next->length < recent->length) { current = current->next; } recent->next = current->next; current->next = recent; } } } // print the sorted chained list current = head; while (current->next) { printf("%s\n", current->data); current = current->next; } // free the list current = head; while (current->next) { recent = current; current = current->next; free(recent); } return (0); } 

一个非常简单的版本可能看起来像这样。 这是一个冒泡排序 ,对于任何合理的大小数据都很慢,但看起来你只排序了11个元素,所以这里无关紧要。

关键是’if’语句,用于比较两个数组位置的长度。 如果它们出现故障,接下来的三行将交换它们。

 char* temp; int length = 11; int step, i; for(step = 0; step < length - 1; step++) for(i = 0; i < length - step - 1; i++) { if(strlen(ptstr[i]) > strlen(ptstr[i+1])) { temp = ptstr[i]; ptstr[i] = ptstr[i + 1]; ptstr[i + 1] = temp; } } 

编辑:如果要按字符串的内容排序而不是长度,则将if语句更改为:

 if(strcmp(ptstr[i], ptstr[i + 1]) > 0) 

(注意:你最好尽可能使用str n cmp)