java - 如何找到给定字符串中最长的单词?

标签 java string

在给定的字符串中,我想找到最长的单词,然后将其打印在控制台中。

我得到的输出是第二长的单词,即“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/

相关文章:

python - 如何读取没有标题或 mimetype 的 Gzip 字符串?使用 Python

c# - 如何从 C# 中的字符串中删除多个、重复和不必要的标点符号?

javascript - 在保留括号的同时将数组转换为字符串

c++ - 如何将 char 字符串转换为 wchar_t 字符串?

java - 使用类元数据序列化 JSON

java - 锁定外部线程还是内部线程?

java - 使用 Java Zxing API 将条码内容写为条码下方的标签

java - 结合对象的 ArrayList 并在 Java 中对 BigDecimal 求和

java - 从头开始实现ADT链表

c - 如何检查子字符串的实例是否在字符串的末尾并且仅一次(比如使用 strstr)?