ICSE Class 10 Computer Applications
Question 24 of 46
String Handling — Question 24
Back to all questions 24
Question Question 11
Write a program in Java to enter a string/sentence and display the longest word and the length of the longest word present in the string.
Sample Input:
"Tata football academy will play against Mohan Bagan"
Sample Output:
The longest word: Football
The length of the word: 8
import java.util.Scanner;
public class KboatLongestWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
str += " "; //Add space at end of string
String word = "", lWord = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
if (word.length() > lWord.length())
lWord = word;
word = "";
}
else {
word += ch;
}
}
System.out.println("The longest word: " + lWord +
": The length of the word: " + lWord.length());
}
}Output
