在给定的字符串中,我想查找最长的单词并打印相同的单词。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());
}
}