VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-word-is-present-in-a-sentence/

⇱ Check if a word is present in a sentence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a word is present in a sentence

Last Updated : 12 Jul, 2025

Given a sentence as a string str and a word word, the task is to check if the word is present in str or not. A sentence is a string comprised of multiple words and each word is separated with spaces.
Examples: 

Input: str = "Geeks for Geeks", word = "Geeks" 
Output: Word is present in the sentence 


Input: str = "Geeks for Geeks", word = "eeks" 
Output: Word is not present in the sentence 

Approach: In this algorithm, stringstream is used to break the sentence into words then compare each individual word of the sentence with the given word. If the word is found then the function returns true. 
Note that this implementation does not search for a sub-sequence or sub-string, it only searches for a complete single word in a sentence.
Below is the implementation for the case-sensitive search approach: 


Output: 
Yes

 

Time complexity: O(n) where n is the length of the sentence.

Auxiliary space: O(n) where n is the length of string.

Below is the implementation for the case-insensitive search approach: 
 


Output: 
Yes

 

Time complexity: O(length(s))

Auxiliary space: O(1)

Method #3:Using Built-in Python Functions:

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • We use count() function to check whether the word is in array
  • If the value of count is greater than 0 then word is present in string

Below is the implementation:

Output:

Yes

Time complexity: O(length(s))

Auxiliary space: O(1)

Comment
Article Tags:
Article Tags: