在C中,按字符串长度排序字符串数组
发布时间:2020-12-16 09:55:13 所属栏目:百科 来源:网络整理
导读:所以我将字符串输入到数组mydata [10] [81] while ((ct=10) gets(mydata[ct]) != NULL (mydata[ct++][0] != ' ')) 然后我使用for循环创建第二个指针数组 for (i=0;i11;i++){ ptstr[i] = mydata[i];} 这是我被卡住的地方 我知道我需要以某种方式使用strlen,
|
所以我将字符串输入到数组mydata [10] [81]
while ((ct<=10) && gets(mydata[ct]) != NULL && (mydata[ct++][0] != ' ')) 然后我使用for循环创建第二个指针数组 for (i=0;i<11;i++){
ptstr[i] = mydata[i];
}
这是我被卡住的地方 希望这是有道理的,我很失落如何做或解释它,我只是尝试使用数组位置按长度排序字符串(不使用像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] = {
"watfi","wh","barified","foo"
};
qsort(arr,ROWS,MAXLEN,compare);
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
