C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Longest Word Program - Java Programs

Write a program to input a sentence and print the number of characters found in the longest word of the given sentence.
For example, if s = “India is my country” then the output should be 7.

import java.util.Scanner; class Longest{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.print("Enter the sentence: "); String s = in.nextLine(); String l = ""; String w = ""; for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(ch == ' ' || i == s.length() - 1){ if(w.length() > l.length()) l = w; w = ""; } else if(Character.isLetterOrDigit(ch)) w += ch; } int len = l.length(); System.out.println("Longest word length: " + len); } }

Output

 
 OUTPUT : 
Enter the sentence: India is my country.
Longest word length: 7