strorder.c (1407B)
1 /* Exercise 8.21 */ 2 3 #include <stdio.h> 4 #include <string.h> 5 #include <stdlib.h> 6 #include <ctype.h> 7 8 #define SIZE 20 9 #define BUF 254 10 11 void bsortp(char *string[]); 12 13 int main(void) 14 { 15 char cities[SIZE][BUF], *pointers[SIZE] = { 0 }; 16 int i = 0, j; 17 18 printf("Give me a city (%d to end): ", EOF); 19 gets(cities[i]); 20 21 while( atoi(cities[i++]) != EOF ) { 22 /* convert the string to lowercase */ 23 for(j = 0; j < (int)strlen(cities[i - 1]); j++) 24 cities[i - 1][j] = tolower((int)cities[i - 1][j]); 25 26 printf("Give me a city (%d to end): ", EOF); 27 gets(cities[i]); 28 } 29 30 cities[i - 1][0] = '\0'; /* Remove the '-1' */ 31 32 /* Copy the address of each phrase to pointers[] */ 33 for(i = 0; i < SIZE; i++) 34 pointers[i] = cities[i]; 35 36 bsortp(pointers); /* Order the pointers[] array */ 37 38 /* Print the non-empty strings in the pointer[] */ 39 for(i = 0; i < SIZE; i++) { 40 if( strlen(pointers[i]) ) 41 printf("%s\n", pointers[i]); 42 } 43 44 return 0; 45 } /* E0F main */ 46 47 /* Sort an array of pointers using the BubbleSort alrorithm */ 48 void bsortp(char *string[]) 49 { 50 int i, j; 51 char *tmpp; 52 53 for(i = 1; i < SIZE; i++) { 54 for(j = 0; j < SIZE - 2; j++) { 55 if( strcmp(string[j], string[j + 1]) > 0 ) { 56 /* Swap the addresses */ 57 tmpp = string[j]; 58 string[j] = string[j + 1]; 59 string[j + 1] = tmpp; 60 } 61 } 62 } 63 } /* eof bsortp() */ 64