2017-04-06 34 views
0

与えられた文字列で、私は最も長い単語を見つけて同じものを印刷したいと思います。Java:与えられた文字列の中で最も長い単語を見つけるには?

出力が2番目に長い単語、つまり"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

あなたは、これははるかに良いとクリーンなバージョンであるJavaの8とストリームAPIを使用することができます場合は、

、などの
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

を試すことができます。

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で使用できる1つのライナーです:

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!

それを試してみてください
関連する問題