How to find the longest word in a string with Java

2 Answers

0 votes
import java.util.Arrays;

public class Main {
    public static String longestWord(String s) {
        return Arrays.stream(s.split("\\s+"))
                     .max((a, b) -> Integer.compare(a.length(), b.length()))
                     .orElse("");
    }

    public static void main(String[] args) {
        System.out.println(longestWord("Could you recommend a good restaurant nearby?"));
    }
}



/*
run:

restaurant

*/

 



answered Mar 3 by avibootz
0 votes
public class Main {
    public static String longestWord(String s) {
        String[] words = s.split("\\s+");
        String longest = "";

        for (String w : words) {
            if (w.length() > longest.length()) {
                longest = w;
            }
        }

        return longest;
    }

    public static void main(String[] args) {
        System.out.println(longestWord("Could you recommend a good restaurant nearby?"));
    }
}



/*
run:

restaurant

*/

 



answered Mar 3 by avibootz
...