加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在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];
}

这是我被卡住的地方
我知道我需要以某种方式使用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] = {
        "watfi","wh","barified","foo"
    };
    qsort(arr,ROWS,MAXLEN,compare);
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读