Given a sentence the task is to print the longest word present in the sentence.
Example: Consider the sample text “Lorem Ipsum is simply dummy text of the printing and type setting industry”. The program should find the longest word in this sentence i.e., “printing”.
Note: This program will not print longest words having same number of characters. It will only print the first longest word while scanning the sentence from left to right.
Java
import java.util.*;
public class LongestWord
{
public static void main(String[] args)
{
int l=0,wl=0,max=0;
String str="",word="",mWord="";
char ch=' ';
Scanner sc=new Scanner(System.in);
System.out.print("Enter a sentence:");
str=sc.nextLine();
str=str+" ";
l=str.length();
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch==' ')
{
wl=word.length();
if(wl>max)
{
max=wl;
mWord=word;
}
word="";
}
else
{
word=word+ch;
}
}
System.out.println("Longest Word: "+mWord);
}
}Java