字符串排序。C prime plus的编程练习
提供四种字符串排序方式。
唯一的问题是,VS2019无法运行(提示各种问题,简直让人丧气),DEV却可以顺畅运行。想了三天三夜没想明白为什么。
1 # include <stdio.h> 2 # include <string.h> 3 # include <ctype.h> 4 # define SIZE 5 5 # define LIM 30 6 7 void choice(char *s1[],int n ); 8 void menu(void); 9 void show_arrary(char *s1[], int n); //显示数组 10 void sort(char * s1[], int n); //ASCII 排序 11 void length(char* st[], int n); //字符串长度 12 void sort1(char * s1[], int n); // 首单词长度 13 char* s_get(char* pt, int n); //处理输入 14 int num(char* s1); //计算首单词的数量 15 16 int main() 17 { 18 int ct = 0; 19 char words[SIZE][LIM]; 20 char* pt[SIZE]; 21 puts("Enter 10 strings to the arrary:"); 22 while (ct < SIZE && s_get(words[ct], LIM) && words[ct][0] != '\0') 23 { 24 pt[ct]=words[ct]; 25 ct++; 26 } 27 choice(pt,SIZE); 28 29 return 0; 30 } 31 32 void menu(void) 33 { 34 puts("a. 显示数组内容 b. 以ASCII码的顺序打印字符串"); 35 puts("c. 按长度递增顺序打印字符串 d. 按字符串中第一个单词长度打印字符串"); 36 puts("q.退出程序"); 37 } 38 void choice(char* s1[], int n) 39 { 40 menu(); 41 char ch; 42 43 while ((ch = getchar()) != 'q') 44 { 45 while(ch=='\n') 46 ; 47 switch (ch) 48 { 49 case 'a': show_arrary(s1, n); 50 break; 51 case 'b': sort(s1, n); 52 break; 53 case 'c': length(s1, n); 54 break; 55 case 'd': sort1(s1, n); 56 break; 57 case 'q': 58 break; 59 default: puts("Please enter the right letter:"); 60 } 61 menu(); 62 ch = getchar(); 63 } 64 puts("DONE"); 65 } 66 67 void show_arrary(char * st[],int n) 68 { 69 for (int i = 0; i < n; i++) 70 puts(st[i]); 71 } 72 73 void sort(char * st[], int n) //ASCII 排序 74 { 75 char* temp; 76 for(int i = 0 ; i < n-1;i++) 77 for(int j = i+1; j< n;j++) 78 if (strcmp(st[i],st[j]) > 0) //如果大于0,说明st[i]在st[j]后 79 { 80 temp = st[i]; 81 st[i] = st[j]; 82 st[j] = temp; 83 } 84 for(int i = 0 ;i<n;i++) 85 puts(st[i]); 86 } 87 88 void length(char* st[], int n) //字符串长度排序 89 { 90 char * temp; 91 for (int i = 0; i < n - 1; i++) 92 for (int j = i+1; j < n; j++) 93 if (strlen(st[i]) > strlen(st[j])) 94 { 95 temp = st[i]; 96 st[i] = st[j]; 97 st[j] = temp; 98 } 99 for(int i = 0 ;i<n;i++) 100 puts(st[i]); 101 } 102 103 void sort1(char *s1[], int n) //首单词长度排序 104 { 105 char * temp; 106 for (int i = 0; i < n - 1; i++) 107 for (int j =i+ 1; j < n; j++) 108 if (num(s1[i]) > num(s1[j])) 109 { 110 temp = s1[i]; 111 s1[i] = s1[j]; 112 s1[j] = temp; 113 } 114 for(int i = 0 ;i<n;i++) 115 puts(s1[i]); 116 } 117 118 int num(char * s1) //首单词计数 119 { 120 int ct; 121 122 while (!isalpha(*s1)) 123 s1++; 124 while (isalpha(*s1)) 125 { 126 s1++; 127 ct++; 128 } 129 return ct; 130 } 131 132 char* s_get(char* pt, int n) 133 { 134 char* ret_val; 135 int i = 0; 136 137 ret_val = fgets(pt, n, stdin); 138 if (ret_val) 139 { 140 while (pt[i] != '\n' && pt[i] != '\0') 141 i++; 142 if (pt[i] == '\n') 143 pt[i] = '\0'; 144 else 145 while (getchar() != '\n') 146 continue; 147 } 148 return ret_val; 149 }
                    
                
                
            
        
浙公网安备 33010602011771号