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

问题描述

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

/* 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] != '\0' && s2[i] != '\0')
        ++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,有解释和示例可以帮助您