Given a string S consisting of lowercase English alphabets, the task is to print the longest word present in the given string in python.

Examples:

Input: S = “be confident and be yourself”
Output: “confident”
Explanation:
Words present in the sentence are “be”, “confident”, “and”, “be” and “yourself”.
Length of each of the words are 2, 9, 3, 2, and 8 respectively.
Therefore, the longest word is “confident”.

Input: S = “geeks for geeks”
Output: “geeks”

Searching-based Approach: Refer to this article to solve this problem by performing the following steps:

  • Iterate over the characters of the string.
  • Check if the current character encountered is a space or end of the string is reached.
  • If the current character is found to be so, update the maximum length of a word obtained.
  • Finally, print the longest word obtained using substr() method.

#sorting #strings #technical scripter #python

Python Program to Find The Longest Word in A Sentence
8.85 GEEK