[英]How to sort an array of structures according to values of one of its members, breaking ties on the basis of another member?
[英]how to sort structures with string values
我正在嘗試按字母順序對字典進行排序,該字典由單詞后跟含義的結構組成。 當我運行程序時,第三個結構的 output 顯示為:<<arrow@,並且字典仍然未排序。 我試過調試器,但這似乎沒有幫助。 先感謝您。
/* 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 中的 function strcmp(查看man strcmp以獲得更精確的信息);
次要排序您的“字典”,您可以使用冒泡排序算法,這是一種簡單且適用於您的任務的算法:冒泡排序算法,有解釋和示例可以幫助您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.