868. Count the Number of Words in a Given String

Given a string s consisting of words and spaces, return the number of words in the string.

A word is defined as a sequence of non-space characters separated by at least one space.

Example 1:

Input: s = "Take you forward"

Output: 3

Explanation: The string has 3 words separated by spaces.

Example 2:

Input: s = " Hello  World "

Output: 2

Explanation: Multiple spaces between and around words are ignored.

Now Your Turn!

Pick the correct output for the given input

Input: s = "  "

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= s.length <= 105

The string may contain:

  • lowercase and uppercase English letters
  • digits
  • symbols
  • punctuation
  • multiple spaces (including leading/trailing)
0
class Solution {
public:
int countWords(const string& s) {
// Your code goes here
}
};
Test Case

Input:

S