Last Updated: 16 Mar, 2021

Count Words

Easy

Problem statement

For a given input string(str), find and return the total number of words present in it.

It is assumed that two words will have only a single space in between. Also, there wouldn't be any leading and trailing spaces in the given input string.

Input Format:
The first and only line of input contains a string without any leading and trailing spaces.
Output Format:
The only line of output prints an integer value denoting the total number of words present in the string.
Note:
You are not required to print anything. It has already been taken care of.
Constraints:
0 <= N <= 10^3
Where N is the length of the input string.

Time Limit: 1 sec

Approaches

01 Approach

  • We handle a simple corner case that if the length of the string is 0 we return 0 immediately.
  • Next, we count the number of spaces in the sentence.
  • Since it is given that every pair of words is separated by a space character so our final sequence will look like word [space] word [space] … [word].
  • Hence, if the total words are W, the count of space characters is W - 1.
  • We store the count of spaces inside a variable count and return count + 1 as the total number of words.