一个句子,找出最字符最少的关键词
1 //一个句子,找出最字符最少的关键词,eg practice makes perfect 2 3 public static void main(String[] args) { 4 int minLen=0; 5 String str=null; 6 String sentence="practice makes perfect"; 7 String[] strings=sentence.split(" "); 8 /*for(int i=0;i<strings.length;++i){ 9 System.out.println(strings[i]); 10 }*/ 11 minLen=strings[0].length(); 12 str=strings[0]; 13 for(int i=1;i<strings.length;++i){ 14 if(strings[i].length()<minLen){ 15 minLen=strings[i].length(); 16 str=strings[i]; 17 } 18 } 19 System.out.println("The min keyword is "+str+"\nit's length is "+str.length()); 20 } 21 22 }
运行结果
The min keyword is makes
it's length is 5
注,如果空格个数多于一个,eg. practice makes perfect
运行结果:
The min keyword is
it's length is 0
把第7行改为
String[] strings=sentence.split("\\s{1,}");
或者
String[] strings=sentence.split("\\s+");
就可以了,参考 http://maoa.cn/?post=406
hashmap:
1 public static void main(String[] args) { 2 String sentence="practice makes perfect"; 3 String[] strings=sentence.split("\\s+"); 4 HashMap<Integer,String> map = new HashMap<Integer,String>(); 5 for(int i=0;i<strings.length;++i){ 6 map.put(strings[i].length(), strings[i]); 7 } 8 Iterator<Entry<Integer,String>> iter=map.entrySet().iterator(); 9 Entry<Integer,String> entry=iter.next(); 10 int minLen=entry.getKey(); 11 String str=entry.getValue(); 12 while(iter.hasNext()){ 13 entry=iter.next(); 14 if(entry.getKey()<minLen){ 15 minLen=entry.getKey(); 16 str=entry.getValue(); 17 } 18 } 19 System.out.println("The min keyword is "+str+"\nit's length is "+str.length()); 20 }
posted on 2014-04-16 23:15 crane_practice 阅读(265) 评论(0) 编辑 收藏 举报