c - 在C编程中对字符串与相应的整数数组进行排序

标签 c arrays string sorting

所以我将数字和字母放入数组和字符串中,但它们是相关的 因为 10b 必须是 10b,4b 必须是 4b。

我希望按字母顺序对字符串进行排序,从 a 到 b 到 c...等等

ASCII 奇数字母的数字应按升序排列,而 ASCII 偶数字母的数字应按降序排列。

即如以下情况应为 5a 12a 10b 4b 4h

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

int
main(int argc, char *argv[]) {
    char *alpha[] = {"b", "b", "h", "a", "a"};
    int num[5]= {4,10,4,12, 5};
    int i;

    printf("The classes are ");

    for (i=0; i<5; i++){
    printf("%d%s ", num[i], alpha[i]);
    }
    printf("\n");

    printf("The classes are rearragnged to:");

    return 0;
}

知道如何对它们进行排序吗?

(额外说明:我尝试过冒泡排序,但实际上不适用于数组和字符串...我也将它们都放在一个字符串中,但是当使用 4b 和 10b 排序时,它是随机的,因为它无法比较正确的字符串位置有一位有两位数...)

最佳答案

如果将 alphanum 视为一对,表达这一点的最佳方式通常是将它们组合在一个对象中(然后对这些对象进行排序),而不是管理两个单独的数组(不表达这种“对”关系)。如果 - 由于某种原因 - 您不被允许更改数据结构,那么还有其他方法(如果您愿意,您可以稍后询问)。但让我在这里提出表达“对”意图的解决方案:

struct classStruct {
    char *alpha;
    int num;
};

int compareClassStructByLetter(const void *c1, const void *c2) {
    struct classStruct* c1Ptr = (struct classStruct *)c1;
    struct classStruct* c2Ptr = (struct classStruct *)c2;
    int result = 0;
    int strcmpResult = strcmp(c1Ptr->alpha, c2Ptr->alpha);
    if (strcmpResult != 0) {
        result = strcmpResult;
    }
    else {
        result = c2Ptr->num - c1Ptr->num;   // ascending order...
        char c = *c1Ptr->alpha;
        if (c % 2) { // odd alpha? (for example, 'a'== 65 == odd)?
            result = -result;  // reverse order to descending
        }
    }
    return result;
}

int main(int argc, char *argv[]) {
    int i;
    struct classStruct classes[5] = {
        { "b", 4 },
        { "b", 10 },
        { "h", 4 },
        { "a", 12 },
        { "a", 5 }
    };

    printf("The classes are ");

    for (i=0; i<5; i++){
        printf("%d%s ", classes[i].num, classes[i].alpha);
    }
    printf("\n");

    qsort(classes, 5, sizeof(struct classStruct), compareClassStructByLetter);

    printf("The classes are rearragnged to:");
    for (i=0; i<5; i++){
        printf("%d%s ", classes[i].num, classes[i].alpha);
    }
    printf("\n");

    return 0;
}

该程序的输出是:

The classes are 4b 10b 4h 12a 5a 
The classes are rearragnged to:5a 12a 10b 4b 4h

关于c - 在C编程中对字符串与相应的整数数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976565/

相关文章:

php - 通过 ajax POST json 数据发送一个空数组

时间:2019-03-17 标签:c#string.length

C `SIGVTALRM` 时不处理 `sigwait` 或 `pause`

c - mpi 编译警告隐式声明

C - 将用户输入扫描到要排序的数组中

c - 如何将数组声明为参数不需要第一维的界限?

c - 输入/输出lzw问题

java - 如何从 .t​​xt 文件中读取数字并以单字数字的形式打印出来? IE。 30= 三个零 1= 一

Python 字符串替换

string - Kickstart 2017(apac) 模式重叠