如何使用字符串值对结构进行排序

how to sort structures with string values

我正在尝试按字母顺序对字典进行排序,它由结构组成,单词后跟含义。当我 运行 程序时,第三个结构的输出显示为:<

/* program to sort a dictionary */

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

struct entry
{
    char word [15];
    char definition [50];
};


int compareString (char s1[], char s2[])
{
    int i = 0;
    int answer;

    while (s1[i]== s2[i] && s1[i] != '[=10=]' && s2[i] != '[=10=]')
        ++i;

    if (s1[i] < s2[i])          // s1 < s2
        answer = -1;
    else if (s1[i]== s2[i])      //  s1 == s2
        answer = 0;
    else
        answer =1;                  // s1 > s2

    return answer;
}


void sortString (struct entry dictionary[], int entries)
{
    int compareString (char s1[], char s2[]);
    int i,j;
    int result;
    char temp[85];
    char temp2[85];

    for (i =0; i < entries; ++i)
    {
        for (j=i+1; j < entries; ++j)
        result = compareString(dictionary[i].word, dictionary[j].word);
        if (result < 0)
        {
            strcpy(temp, dictionary[i].word);
            strcpy(temp2, dictionary[i].definition);
            strcpy (dictionary[i].word, dictionary[j].word);
            strcpy (dictionary [i].definition, dictionary[j].definition);
            strcpy (dictionary[j].word, temp);
            strcpy (dictionary[j].definition, temp2);
        }
        else
        {
        continue;
        }
    }
}


int main (void)
{
    void sortString (struct entry dictionary[], int entries);
    int k;

    struct entry myDictionary [10] =
    {   {"arrdvark", "a burrowing African mammal"       },
        {"aigrette", "an ornamental cluster of feathers"},
        {"abyss", "a bottomless pit"                    },
        {"acumen", "mentally sharp; keen"               },
        {"agar", "a jelly made from seaweed"            },
        {"addle", "to become confused"                  },
        {"aerie", "a high nest"                         },
        {"ahoy", "a nautical call of greeting"          },
        {"ajar", "partially opened"                     },
        {"affix", "to append; attach"                   }};


   sortString(myDictionary, 10);

   for (k =0; k <10; ++k)
   {
       printf("%s means %s\n", myDictionary[k].word, myDictionary[k].definition);
    }

    return 0;

}

首先要轻松比较您的字符串,您可以使用您已经包含在 string.h 中的函数 strcmp(查看 man strcmp 以获得更精确的信息);

次要对“字典”进行排序,您可以使用冒泡排序算法,这是一种适合您的任务的简单算法:bubble sort algorithm,其中的解释和示例可以帮助您