Explanation
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.
Algorithm
- Define a string.
- Convert the string to lowercase to make it case-insensitive.
- Add an extra space at the end.
- 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.
- Initialize variable small and large with first word of array.
- Iterate through array words, check if the length of word is less than small. If yes, store that word in small.
- If the length of word is greater than large. If yes, store that word in large.
- At the end, display the smallest and largest word.
Input:
string = "Hardships often prepare ordinary people for an extraordinary destiny"
Output:
Smallest word: an
Largest word: extraordinary
Python
Output:
C
Output:
JAVA
Output:
C#
Output:
PHP
Output: