Home » Program to Find the Largest and Smallest Word in a String

Program to Find the Largest and Smallest Word in a String

by Online Tutorials Library

Program to find the largest & smallest word in a string

Explanation

In this program, we need to find the smallest and the largest word present in the string.

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.

Algorithm

  1. Define a string.
  2. Convert the string to lowercase to make it case-insensitive.
  3. Add an extra space at the end.
  4. Now, iterate through the string till space is found and add those character into variable word. Add each word into words array. Array words will hold all the words present in the string.
  5. Initialize variable small and large with first word of array.
  6. Iterate through array words, check if the length of word is less than small. If yes, store that word in small.
  7. If the length of word is greater than large. If yes, store that word in large.
  8. At the end, display the smallest and largest word.

Solution

Python

Output:

Smallest word: an  Largest word: extraordinary  

C

You may also like