/* 将这些国家名字按照首字母顺序排列 并按照长度排序,从长到短. Afghanistan Bangladesh Bhutan Burma Cambodia China India Indonesia Japan Laos Malaysia Maldives Mongolia Nepal North Korea Pakistan Philippines Singapore South Korea Sri Lanka Turkey Vietnam Palestine Sikkim
*/
#include <stdio.h> #include <string.h> int main() { char* countries[] = { "Afghanistan", "Bangladesh", "Bhutan", "Burma", "Cambodia", "China", "India", "Indonesia", "Japan", "Laos", "Malaysia", "Maldives", "Mongolia", "Nepal", "North Korea", "Pakistan", "Philippines", "Singapore", "South Korea", "Sri Lanka", "Turkey", "Vietnam", "Palestine", "Sikkim" }; //按字母 int len = sizeof(countries)/8; for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (!(strcmp(countries[j], countries[j+1]))) { char* temp = countries[j]; countries[j] = countries[j+1]; countries[j+1] = temp; } } } for (int i = 0; i < len; i++) { printf("%s\n",countries); }
printf("---------------\n"); //按长度 for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { unsigned long len1 = strlen(countries[j]); unsigned long len2 = strlen(countries[j+1]); if (len1 < len2) { char* temp = countries[j]; countries[j] = countries[j+1]; countries[j+1] = temp; } } } for (int i = 0; i < len; i++) { printf("%s\n",countries); } return 0; }
|