Java Program to Find the longest word in a String

(319 Views)


You have to write a program in Java which will find the longest word in the String.
For eg.
Input: That building is very tall.
Output: building
In above example "building" is the longest word in the given string i.e "That building is very tall."

Find the longest word in a String using java
public class FindLarge { private String longestWord; public String longestWord(String sen) { String arr[] = sen.split(" "); // seperates each word in the string and stores it in array longestWord = arr[0]; // Assume first word to be the largest word for (String a : arr) if (longestWord.length() < a.length()) // check length of each word longestWord = a; return longestWord; } public static void main(String[] args) { FindLarge fl=new FindLarge(); String longestWord=fl.longestWord("Hello Welcome to Java"); // string to be checked System.out.println("Longest Word: "+ longestWord); // Final Output } }

Solution Worked 2 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search