在C

时间:2018-05-16 14:14:49

标签: c arrays string sorting for-loop

我的任务是使用指针数组解决以下问题:

为一个按照命令列出字符串的函数编写两个原型 字符串长度 - 最短到最长。在第一个,功能应该期望一个 输入/输出参数,是一个二维的字符数组 字符串最多包含STRSIZ字符。在第二个,功能应该 期望输入/输出参数是一个指针数组。

我目前已经为此编写了这段代码,似乎无法说明为什么它对我来说无法正常工作:

int number;
int a;
int b;
char placeholder;
char words[100];
char wordscopy[100];

printf("Enter the amount of words or names you wish to sort (0 - 100) :\n");
scanf_s("%d", &number);

printf("Enter names or words on separate lines\n");
for (a = 0; a < number; ++a)
scanf_s("%s", &words[a]);

for (a = 0; a < number; ++a)
    words[a] = wordscopy[a];

for (a = 0; a < number; ++a)
{
    for (b = a + 1; b < number; ++b)
    {
        if (strlen(wordscopy[a]) < strlen(wordscopy[b]))
        {
            placeholder = wordscopy[a];
            wordscopy[a] = wordscopy[b];
            wordscopy[b] = placeholder;
        }
    }
}
printf("\n\n%-30s%5c%-30s\n\n", "Original Order", ' ',"Least Letters to Most Letters");
for (a = 0; a < number; ++a)
printf("%-30s%5c%-30s\n", words[a], ' ', wordscopy[a]);
printf("\n\n");


return 0;

我对编码很新,我似乎无法找出该程序为何对我不起作用。

输出应为:

Original Order               Least Letters to Most Letters
Brad                         Brad
Matthew                      Megan
Brandon                      Brandon
Megan                        Matthew
Melissa                      Melissa

1 个答案:

答案 0 :(得分:0)

您可以使用qsort按字符串大小对字符串进行排序

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

#define MAXLEN 25

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 num_words;
    scanf("%d", &num_words);

    char word[MAXLEN];


    char input[num_words][MAXLEN];
    for(int i = 0; i < num_words; i++ ) {
        scanf("%s", word);
        strcpy(input[i], word);
    }

    qsort(input, num_words, MAXLEN, compare);
    for(int i = 0; i < num_words; i++)
        printf("%s\n", input[i]);
    return 0;
}

结果按字符串大小排序:

Input:              Output:

Brad                Brad
Matthew             Megan
Brandon             Brandon
Megan               Melissa
Melissa             Matthew