KnowledgeBoat Logo
|
LoginJOIN NOW

Computer Applications

Define a class StringMinMax to find the smallest and the largest word present in the string.

E.g.
Input:
Hello this is wow world

Output:
Smallest word: is
Largest word: Hello

Java

Java String Handling

9 Likes

Answer

import java.util.Scanner;

public class StringMinMax
{
    public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       System.out.println("Enter a sentence:");
       String str = in.nextLine();
       
       str += " "; 
       String word = "", lWord = "", sWord = str;
       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;
                else if (word.length() < sWord.length())
                    sWord = word;
                    
                word = "";
           }
           else {
               word += ch;
           }
       }
       
       System.out.println("Smallest word: " + sWord);
       System.out.println("Longest word: " + lWord);
    }
}

Output

BlueJ output of Define a class StringMinMax to find the smallest and the largest word present in the string. E.g. Input: Hello this is wow world Output: Smallest word: is Largest word: Hello

Answered By

3 Likes


Related Questions