Find Longest Word in a String in Java

Write a program to input a sentence and print the longest word or words in it, and the average length of words to the nearest whole number.

Example:
INPUT: The good Lord gave us a good meal.
OUTPUT: good Lord gave good meal
Average length: 3

Program:

import java.io.*;
class Longest{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Sentence: ");
        String s = br.readLine();
        String word = new String();
        int len = 0;
        int sum = 0;
        int count = 0;
        int avg = 0;
        s = s.replace(".", "");
        s = s.replace(",", "");
        s = s.replace("?", "");
        s = s.trim();
        s += " ";
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch == ' '){
                if(len < word.length())
                    len = word.length();
                sum += word.length();
                word = new String();
                count++;
            }
            else
                word += ch;
        }
        System.out.print("Longest words: ");
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch == ' '){
                if(len == word.length())
                    System.out.print(word + "\t");
                word = new String();
            }
            else
                word += ch;
        }
        avg = (int)(Math.rint((double)sum / count));
        System.out.println("\nAverage length: " + avg);
    }
}

1 thought on “Find Longest Word in a String in Java

  1. Sir,a program is given which states that:
    WAP in Java to accept a paragraph containing n no of sentences where n>=1&& n<4. The words are to be separated with a single blank space and are in upper case.A sentence may be terminated either with a '.', '?' ,'!' only. Any other character may be ignored. Perform the following operations:
    1) Accept the no.of sentences. If the number of sentences exceeds the limit, an appropriate error message must be displayed.
    2)Find the number of words in the whole paragraph.
    3) Display the words in ascending order of their frequency. Words with same frequency may appear in any order.
    Eg:
    Sample Input:
    Enter number of sentences:1
    Enter sentences:TO BE OR NOT TO BE.
    Sample Output:
    Total number of words:6
    WORD FREQUENCY
    OR 1
    NOT 1
    TO 2
    BE 2

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.