帶有字串功能的 C 程式,用於按字母順序對名稱進行排序。
問題
使用氣泡排序技術,按字母順序對使用者在執行時提供的名稱進行排序。
解決方案
用於按字母順序列印名稱的邏輯如下 -
for (i=1; i < ITEMS; i++){ for (j=1; j <= ITEMS-i ; j++){ if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */ strcpy (dummy, string[j-1]); strcpy (string[j-1], string[j]); strcpy (string[j], dummy ); } } }
例子
以下是使用字串函式按字母順序對名稱進行排序的 C 程式 -
#define ITEMS 5 #define MAXCHAR 20 main( ){ char string[ITEMS][MAXCHAR], dummy[MAXCHAR]; int i = 0, j = 0; /* Reading the list */ printf ("Enter names of %d items
",ITEMS); while (i < ITEMS) scanf ("%s", string[i++]); /* Sorting begins */ for (i=1; i < ITEMS; i++){ for (j=1; j <= ITEMS-i ; j++){ if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */ strcpy (dummy, string[j-1]); strcpy (string[j-1], string[j]); strcpy (string[j], dummy ); } } } printf ("
Alphabetical list
"); for (i=0; i < ITEMS ; i++) printf ("%s
", string[i]); }
輸出
當執行上述程式時,它會產生以下輸出 -
Enter names of 5 items computers architecture organization microprocessor networking Alphabetical list architecture computers microprocessor networking organization
廣告