2017-04-06 69 views
0

在给定的字符串中,我想查找最长的单词并打印相同的单词。Java:如何找到给定字符串中最长的单词?

我得到的输出是第二长的单词,即"Today",但我应该得到"Happiest"
我可以知道我做错了什么,或者有更好的/不同的方法来查找字符串中最长的单词吗?

public class DemoString 
{ 
    public static void main(String[] args) 
    { 
     String s="Today is the happiest day of my life"; 
     String[] word=s.split(" "); 
     String rts=" "; 
     for(int i=0;i<word.length;i++){ 
      for(int j=1+i;j<word.length;j++){ 
       if(word[i].length()>=word[j].length()){ 
        rts=word[i]; 
       } 
      } 
     } 
     System.out.println(rts); 
     System.out.println(rts.length()); 
    } 
} 

回答

1

相反,它应该是:

for(int i=0;i<word.length;i++){ 
    if(word[i].length()>=rts.length()){ 
     rts=word[i]; 
    } 
} 
0

你可以尝试像,

String s="Today is the happiest day of my life"; 
    String[] word=s.split(" "); 
    String rts=" "; 
    for(int i=0;i<word.length;i++){ 
    if(word[i].length()>=rts.length()){ 
     rts=word[i]; 
    } 
    } 
    System.out.println(rts); 
    System.out.println(rts.length()); 
-1

如果你可以使用Java 8和流API,这是一个更好的和更清洁的版本。

String s="Today is the happiest day of my life"; 
    Pair<String, Integer> maxWordPair = Arrays.stream(s.split(" ")) 
         .map(str -> new Pair<>(str, str.length())) 
         .max(Comparator.comparingInt(Pair::getValue)) 
         .orElse(new Pair<>("Error", -1)); 
    System.out.println(String.format("Max Word is [%s] and the length is [%d]", maxWordPair.getKey(), maxWordPair.getValue())); 

您将删除所有for循环,只会导致错误和验证。

-1
for(int i=0;i<word.length;i++){ 
      for(int j=0;j<word.length;j++){ 
       if(word[i].length()>=word[j].length()){ 
        if(word[j].length()>=rts.length()) { 
         rts=word[j]; 
        } 
       } else if(word[i].length()>=rts.length()){ 
        rts=word[i]; 
       } 

      } 
     } 
1

这里是一个班轮你可以使用Java 8使用:

import java.util.*; 

class Main { 
    public static void main(String[] args) { 
    String s ="Today is the happiest day of my life"; 
    System.out.println(Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null)); 
    } 
} 

输出:

happiest 

试试吧here!

相关问题