方法一:(用sort排序)(#include<algorithm>)
- #include<iostream>
- #include<algorithm>
- #include<cstdio>
- #include<string>
- using namespace std;
- const int maxn=105;
- string str[maxn];
- void print1(string s,int maxlen){ //在字符串后面加上空格以满足要求
- int len=maxlen-s.length();
- while(len--){
- s+=" ";
- }
- cout<<s;
- }
- int main(){
- int n;
- while(cin>>n){
- int maxlen=0;
- for(int i=0;i<n;i++){
- cin>>str[i];
- if(maxlen<str[i].length())maxlen=str[i].length();
- }
- printf("------------------------------------------------------------\n");
- sort(str,str+n);
- int coloum=(60-maxlen)/(maxlen+2)+1;
- int row=(n-1)/coloum+1;
- for(int i=0;i<row;i++){
- for(int j=i;j<coloum*row && j<n;j+=row){
- if(j==row*(coloum-1))print1(str[j],maxlen); //每行的最后一个字符串
- else print1(str[j],maxlen+2);
- }
- cout<<endl;
- }
- }
- return 0;
- }
方法二:(用去qsort排序)(位于库函数 #include<stdlib.h>)
- #include<cstdio>
- #include<cstring>
- #include<cstdlib>
- using namespace std;
- const int maxn=105;
- int cmp_str(const void *a,const void *b) //本题用qsort排序二维字符数组,故需要编写比较函数
- {
- return strcmp((char*)a,(char*)b);
- }
- void print1(const char * s,int maxlen){ //打印字符串,没达到长度则通过空格补充
- printf("%s",s);
- int len=maxlen-strlen(s);
- while(len--){
- printf(" ");
- }
- }
- int main()
- {
- int n;
- while(scanf("%d",&n)==1){
- char str[maxn][65];
- int maxlen=0;
- for(int i=0;i<n;i++){
- scanf("%s",str[i]);
- if(maxlen<strlen(str[i]))maxlen=strlen(str[i]);
- }
- printf("------------------------------------------------------------\n");
- qsort(str, n, sizeof(str[0]), cmp_str);
- int coloum=(60-maxlen)/(maxlen+2)+1;
- int row=(n-1)/coloum+1;
- for(int i=0;i<row;i++){
- for(int j=i;j<coloum*row && j<n;j+=row){
- if(j==row*(coloum-1))print1(str[j],maxlen);
- else print1(str[j],maxlen+2);
- }
- printf("\n");
- }
- }
- return 0;
- }
注意:sort是qsort的升级版,能用sort就最好使用sort.