在给定的字符串中,我想找到最长的单词,然后将其打印在控制台中。
我得到的输出是第二长的单词,即“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 longword = " ";
for (int i = 0; i < word.length; i++)
for (int j = 1 + i; j < word.length; j++)
if (word[i].length() >= word[j].length())
longword = word[i];
System.out.println(longword + " is the longest word with " + longword.length() + " characters.");
System.out.println(rts.length());
}
}
最佳答案
这是一个可以与 Java 8 流 API 一起使用的“one-liner”:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
String s = "Today is the happiest day of my life";
String longest = Arrays.stream(s.split(" "))
.max(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println(longest);
}
}
输出:
happiest
尝试一下 here .
关于java - 如何找到给定字符串中最长的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251808/