字符串排序


字符串排序

时间 限制:
1000ms
内存限制:
65536kB
描述
先输入你要输入的字符串的个数。然后换行输入该组字符串。每个字符串以回车结束,每个字符串少于一百个字符。如果在输入过程中输入的一个字符串为“stop”,也结束输入。
然后将这输入的该组字符串按每个字符串的长度,由小到大排序,按排序结果输出字符串。
输入
字符串的个数,以及该组字符串。每个字符串以‘\n’结束。如果输入字符串为“stop”,也结束输入.
输出
将输入的所有字符串按长度由小到大排序输出(如果有“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
提示
根据输入的字符串个数来动态分配存储空间(采用new()函数)。每个字符串会少于100个字符。
测试数据有多组,注意使用while()循环输入。 
代码1:
import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
import java.util.Scanner;  
public class Main{  
public static void main(String[] args) {  
Scanner sc=new Scanner(System.in);  
ArrayList<String> al=new ArrayList<String>();  
while(sc.hasNextInt()){  
int n=sc.nextInt();sc.nextLine();  
al.clear();  
for(int i=0;i<n;i++){  
String s=sc.nextLine();  
if("stop".equals(s)){  
break;  
}  
else{  
al.add(s);  
}  
  
}  
Collections.sort(al,new MySort());  
for(String t:al)  
System.out.println(t);  
}  
}  
  
}  
class MySort implements Comparator<String>{  
  
public int compare(String o1, String o2) {  
return o1.length()-o2.length();  
}  
  
}//重新定义一个排序器按从小到大排序  

代码2:
import java.io.BufferedReader;  
import java.io.InputStreamReader;  
import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
  
public class Main {  
        public static void main(String[] args) throws Exception{  
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
        ArrayList<Cenlen> ss=new ArrayList<Cenlen>();  
          
        while(true){  
            ss.clear();  
            int n=Integer.parseInt(br.readLine());  
            for(int i=1;i<=n;i++){  
                String s=br.readLine();  
                if("stop".equals(s)){  
                    break;  
                }  
                else{  
                    ss.add(new Cenlen(s));  
                }  
                  
            }  
            Collections.sort(ss);  
            for(Cenlen x:ss){  
                System.out.println(x.s);  
            }  
        }  
  
    }  
}  
        class Cenlen implements Comparable<Cenlen>{  
            String s;  
            int len;  
            Cenlen(String s){  
                this.s=s;this.len=s.length();  
            }  
  
            public int compareTo(Cenlen o) {  
                return this.len-o.len;  
            }  
              
        }

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值