字符串排序
作者:互联网
1 #include<stdio.h> 2 #include<string.h> 3 #define LIM 5 4 #define SIZE 20 5 6 char * s_gets(char *st, int n); 7 void StrSort(char * st[], int n, int opt); 8 9 int main(){ 10 int ct = 0, i = 0, opt; 11 char words[LIM][SIZE]; 12 char * string[LIM]; 13 14 //输入 15 while(ct < LIM && s_gets(words[ct], SIZE) != NULL && words[ct][0] != '\0'){ 16 string[ct] = words[ct]; 17 ct++; 18 } 19 20 21 //排序后输出 22 fputs("选择0为降序,1为升序:", stdout); 23 scanf("%d", &opt); 24 StrSort(string, ct, opt); 25 for(;i < ct; i++){ 26 puts(string[i]); 27 } 28 return 0; 29 } 30 31 //为字符串按字母顺序排序 32 void StrSort(char * st[], int n, int opt){ 33 int i, j; 34 char * temp; 35 36 for(i=0; i < n - 1; i++){ 37 for(j = i + 1; j < n; j++){ 38 if(opt > 0){ 39 if(strcmp(st[i], st[j]) > 0){ 40 temp = st[i]; 41 st[i] = st[j]; 42 st[j] = temp; 43 } 44 }else{ 45 if(strcmp(st[i], st[j]) < 0){ 46 temp = st[i]; 47 st[i] = st[j]; 48 st[j] = temp; 49 } 50 } 51 } 52 } 53 } 54 55 56 //处理输入 57 char * s_gets(char *st, int n){ 58 fgets(st, n, stdin); 59 char *find = strchr(st, '\n'); 60 if(find){ 61 *find = '\0'; 62 } 63 return st; 64 }
标签:opt,temp,int,st,char,字符串,排序,ct 来源: https://www.cnblogs.com/xingyboy/p/16441661.html