Tutorialspoint
Problem
Solution
Submissions

Number of Words in a String

Certification: Basic Level Accuracy: 45.45% Submissions: 11 Points: 5

Write a C++ program that counts the number of words in a given string. A word is defined as a sequence of non-space characters.

Example 1
  • Input: string = "Hello World"
  • Output: 2
  • Explanation:
    • Step 1: Split the input string by spaces.
    • Step 2: Count the number of non-empty elements.
    • Step 3: Return the count.
Example 2
  • Input: string = " This is a test "
  • Output: 4
  • Explanation:
    • Step 1: Split the input string by spaces.
    • Step 2: Count the number of non-empty elements after removing leading and trailing spaces.
    • Step 3: Return the count.
Constraints
  • 1 ≤ len(string) ≤ 10^6
  • String contains printable ASCII characters
  • Time Complexity: O(n), where n is the length of the string
  • Space Complexity: O(1)
ArraysStringsHCL TechnologiesSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate through the string and count the number of transitions from space to non-space characters.
  • Handle leading and trailing spaces separately.
  • Consider edge cases where the string is empty or contains only spaces.

Steps to solve by this approach:

 Step 1: Define a function countWords that takes a constant string reference.

 Step 2: Initialize a counter variable to 0 and a boolean flag (inWord) to track if we're inside a word.
 Step 3: Iterate through each character in the string.
 Step 4: If the character is not a space and we're not currently in a word, increment the counter and set inWord to true.
 Step 5: If the character is a space, set inWord to false.
 Step 6: Return the final count after processing all characters.

Submitted Code :