![]() |
VOOZH | about |
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:
wordCount to 0.wordCount.wordCount to account for the last word.wordCount.Below is the implementation of the algorithm:
Number of words: 5
Time Complexity: O(N) where N is the length of the sentence.
Auxiliary Space: O(1)