gpt4 book ai didi

c - 如何根据每个数字的长度对数组进行排序?

转载 作者:行者123 更新时间:2023-11-30 16:28:26 25 4
gpt4 key购买 nike

我有一个像这样的数组:

arr[] = {0010,1,001,01}

我需要根据数组的位数按升序对数组进行排序,输出应该是:

arr[] = {1,01,001,0010}

我尝试获取每个元素的位数并将其保存在另一个数组中,例如:

digits[] = {4,1,3,2} 

当我对 digits[] 进行排序时,它应该反射(reflect)在 arr[]

最佳答案

您可以将 qsort 与自定义比较函数一起使用,如下所示:

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

const char* arr[] = {"0000","0","000","00"};


int myCompare (const void * a, const void * b ) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;

return strcmp(pa,pb);
// or as below if you compare length only
/*
return strlen(pa)-strlen(pb);
*/
}

int main() {
int i;

int stringLen = sizeof(arr) / sizeof(char *);
qsort(arr, stringLen, sizeof(char *), myCompare);

for (i=0; i<stringLen; ++i)
printf("%d: %s\n", i, arr[i]);
}

输出将是:

0: 0    
1: 00
2: 000
3: 0000

关于c - 如何根据每个数字的长度对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52379197/

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