1 //讀入字符串,並排序字符串 2 #include <stdio.h> 3 #include <string.h> 4 #define SIZE 81 5 #define LIM 20 6 #define HALT "" 7 8 void stsrt(char * strings [], int num); //字符串排序函數 9 char * s_gets(char * st,int n); 10 11 int main(void) 12 { 13 char input[LIM][SIZE]; 14 char *ptstr[LIM]; 15 int ct =0; 16 int k; 17 18 printf("Input up to %d lines,and I will sort them.\n",LIM); 19 printf("To stop,press the Enter key at a line's start.\n"); 20 21 while(ct<LIM && s_gets(input[ct],SIZE)!= NULL && input[ct][0]!='\0') 22 { 23 ptstr[ct] = input[ct]; //設置指針指向字符串 24 ct++; 25 } 26 stsrt(ptstr,ct); //字符串排序函數 27 puts("\nHere's the sorted list:\n"); 28 for (k=0;k<ct;k++) 29 puts(ptstr[k]); 30 return 0; 31 } 32 33 void stsrt(char *strings [], int num) 34 { 35 char *temp; 36 int top,seek; 37 38 for(top=0;top <num -1;top++) 39 for(seek=top+1;seek<num;seek++) 40 if(strcmp(strings[top],strings[seek])>0) 41 { 42 temp = strings[top]; 43 strings[top] = strings[seek]; 44 strings[seek] = temp; 45 } 46 } 47 48 49 50 char * s_gets(char * st, int n) 51 { 52 char * ret_val; 53 int i=0; 54 55 ret_val = fgets(st, n, stdin); //讀取成功,返回一個指針,指向輸入字符串的首字符; 56 if(ret_val) 57 { 58 while(st[i]!='\n' && st[i]!='\0') 59 i++; 60 if(st[i] =='\n') //fgets會把換行符也吃進來了,fgets會在末尾自動加上\0; 61 st[i]='\0'; 62 else //其實是'\0' 63 while(getchar() != '\n') //會把緩沖區后續的字符都清空 64 continue; 65 } 66 return ret_val; 67 }
程序解讀:
這個程序的好處是利用字符串指針數組ptstr進行排序,並未改變input,這樣也保留了input數組中的原始順序。這樣的做法比直接用strcpy()交換兩個input字符串要簡單得多。
程序中還出現了,選擇排序算法:(selection sort algorithm):其實就是以strcmp函數為基礎來冒泡排序指針
C庫中有更高級的排序函數:qsort(),該函數使用一個指向函數的指針進行排序比較。