You can find Longest word in a sentence in java. This is the most famous question of interviewer to find longest word in a sentence, Here i am giving java code to find longest word. In this java example we are using JOptionPane.showInputDialog(“—“), method of javax.swing package to accept input using dialog box. This technique of find longest word can implements in any programming language.
// Find Longest Word in a sentence in java import javax.swing.*; class LongStr { public static void main(String arg[]) { String name=JOptionPane.showInputDialog("Enter a sentence"); name+=" "; String str="",lword=""; for(int i=0;i < name.length();i++) { str+=name.charAt(i); if(name.charAt(i)==' ') { if(str.length() > lword.length()) { lword=str; } str=""; } } System.out.println("Longest Word in a Sentence : "+lword); } }
This is very interesting Sir. Thank you for sharing it with us