Write a java program to find longest word in the sentence

Write a Program which finds the longest word from a sentence. Your program should read a sentence as input from user and return the longest word. In case there are two words of maximum length return the word which comes first in the sentence.

 Input and Output Format:

Input consists of a string with maximum size of 100 characters.

Output consists of a single string.

Refer sample output for formatting specifications.

Sample Input 1:

Welcome to the world of Programming

Sample Output 1:

Programming

Sample Input 2:

ABC DEF

Sample Output 2:

ABC

Java program to find longest word in the sentence.

package testCases;
import java.util.Scanner;
import java.util.StringTokenizer;
 
public class MainJava {
 
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1= sc.nextLine();
System.out.println(lengthiestString(s1));
}
public static String lengthiestString(String s1) {
int max=0;
String s2=new String();
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens()){
String s3=t.nextToken();
int n=s3.length();
if(n>max){
max=n;
s2=s3;}
}
return s2;
}
 
}

 

Add a Comment

Your email address will not be published. Required fields are marked *

one × two =