2017-04-06 407 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!

相關問題