VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-count-the-number-of-words-in-a-sentence/

⇱ Program to count the number of words in a sentence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to count the number of words in a sentence

Last Updated : 18 Jan, 2024

Write a program to count the number ofwords in a given sentence. A word is defined as a sequence of characters separated by spaces.

Examples:

Input: "The quick brown fox"
Output: 4
Explanation: The sentence has four words - "The", "quick", "brown", "fox".

Input: "The quick brown fox"
Output: 4
Explanation: The sentence has four words - "The", "quick", "brown", "fox".

Approach: To solve the problem, follow the below idea:

Iterate through each character in the sentence and count the number of spaces to identify the separation between words. The total count of spaces plus 1 gives the number of words.

Step-by-step algorithm:

  • Initialize a variable wordCount to 0.
  • Iterate through each character in the sentence.
  • Check if the current character is a space.
  • If a space is found, increment the wordCount.
  • After the loop, add 1 to wordCount to account for the last word.
  • Output the final value of wordCount.

Below is the implementation of the algorithm:


Output
Number of words: 5

Time Complexity: O(N) where N is the length of the sentence.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: