Monday 6 December 2021

Java Program to find the largest and smallest word in a string.

largest_word

Java Program to find the largest and smallest word in a string.

In this program, we need to find the smallest and the largest word present in the string:
"Hardships often prepare ordinary people for an extraordinary destiny"

Consider above example in which 'an' is the smallest word and 'extraordinary' is the largest word. One of the approach to find smallest and largest word is to split string into words then, compare length of each word with variables small and large. If length of a word is less than length of small then, store that word in small. If length of a word is greater than length of large then, store that word in large.

string 1

Hardships often prepare ordinary people for an extraordinary destiny

Program

class SmallestLargestWord {

  public static void main(String[] args)   {

    //declare string

   String str1="Hardships often prepare ordinary people for an extraordinary destiny";;

      String word = "", small = "", large="";

    String[] words = new String[100];

    int length = 0;

      //Add extra space after string to get the last word in the given string

      string = string + " ";

    for (int i = 0; i < string.length(); i++){

        if(string.charAt(i) != ' '){

          word = word + string.charAt(i);

      }

  else

    {

      words[length] = word;

      length++;

      word = "";

      }

  }

      //Initialize small and large with first word in the string

    small = large = words[0];

    for (int k = 0; k < length; k++){

      if (small.length() > words[k].length())

        small = words[k];

      if (large.length() < words[k].length())

          large = words[k];

    }

    System.out.println("Smallest word: " + small);

    System.out.println("Largest word: " + large);

      }

    }

   }

output

Smallest word:    an
Largest word:    extraordinary

Theory

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...