小编Sur*_*raj的帖子

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

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

我得到的输出是第二长的单词 ie "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() + …
Run Code Online (Sandbox Code Playgroud)

java string

1
推荐指数
3
解决办法
4万
查看次数

标签 统计

java ×1

string ×1