0054:字符串排序 list<String>的排序使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sdz20172133/article/details/82319398

0054:字符串排序

总时间限制: 

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()循环输入。

来源

06级计算概论课


这题困扰了我很久的就是输入的问题,n的不能用cinnextLine(),会影响到下一个字符串的输入.

import java.util.*;


public class Main {
	
	public static void main(String[] args){
	Scanner cin=new Scanner(System.in);
	
	
    while(cin.hasNextLine())
	{
    List<String> s1 =new ArrayList<>();
    int n = Integer.parseInt(cin.nextLine());
	  for(int i=1;i<=n;i++){
	    String s =cin.nextLine();
	    //System.out.println(s);
	    if(s.equals("stop"))
	   break;
	    else 
	    	s1.add(s);
	    	
	   } 
	  //System.out.println(s1.size());
	   Collections.sort(s1,new StringComparator());
	   Iterator<String> it = s1.iterator();
	   while(it.hasNext()) {
		System.out.println(it.next());
	   }
	}
 
	  
	}
	private static class StringComparator implements Comparator<String>{
		public int compare(String o1,String o2) {
		   int len1 = o1.length();
		   int len2 = o2.length();
		   if(len1!=len2)
		   return len1-len2;
		   else 
		   return o1.compareTo(o2);
		}
	}
  
}


	

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/82319398