字符串排序

复制代码
 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 } 
复制代码

 

posted @   星雨boy  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示