【算法练习】字符串处理 百练poj2915:字符串排序

题目链接:http://bailian.openjudge.cn/practice/2915

2915:字符串排序

总时间限制: 

1000ms

内存限制: 

65536kB

描述

先输入你要输入的字符串的个数。然后换行输入该组字符串。每个字符串以回车结束,每个字符串少于一百个字符。如果在输入过程中输入的一个字符串为“stop”,也结束输入。
然后将这输入的该组字符串按每个字符串的长度,由小到大排序,按排序结果输出字符串。

输入

字符串的个数,以及该组字符串。每个字符串以‘\n’结束。如果输入字符串为“stop”,也结束输入.

输出

扫描二维码关注公众号,回复: 12445581 查看本文章

将输入的所有字符串按长度由小到大排序输出(如果有“stop”,不输出“stop”)。
 

样例输入

5
sky is grey
cold
very cold
stop
3
it is good enough to be proud of
good
it is quite good

样例输出

cold
very cold
sky is grey
good
it is quite good
it is good enough to be proud of

题目理解:

这个题目比较简单,就是写一个cmp函数排序一下,

重要的是输入的时候按行输入,前面有一个整数n

所以要清一下缓存

cin>>n;

string s="\n";

getline(cin,s);

getline(cin,str)

AC代码:

#include<iostream>
#include <algorithm>
using namespace std;

string str[100];
int n;

bool cmp(string a,string b){
    //按照长度从小到大排序输出
    int lena=a.length();
    int lenb=b.length();
    return lena<lenb;
}
int main(){
    while(cin>>n){
        int num=0;
        string s="\n";
        getline(cin,s);   //清除\n的缓存
        while(n--){
            getline(cin,str[num]);  //输入一行字符串
            if(str[num]=="stop") break;
            num++;
        }
        sort(str,str+num,cmp);
        for(int i=0;i<num;i++){
            cout<<str[i]<<endl;
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40760678/article/details/100074823