Count words in a sentence
Count whitespace-separated words in a string, treating consecutive whitespace characters as one separator.
Course progress
Problem 57 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = " Write code, test it well "
Expected output
5
What is happening?
Whitespace separates the five word tokens Write, code,, test, it, and well. Consecutive spaces do not create empty words.
Solution strategy
Build the right mental model
Track whether the scan is currently inside a word and increment the count only when a non-whitespace character starts a new word.
Core concepts
strings · state tracking
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for count-words
using System;
class Program
{
static int CountWords(string text)
{
int count = 0;
bool insideWord = false;
foreach (char symbol in text)
{
if (char.IsWhiteSpace(symbol)) insideWord = false;
else if (!insideWord) { count++; insideWord = true; }
}
return count;
}
static void Main()
{
Console.WriteLine(CountWords(" Write code, test it well "));
}
}Knowledge check
Questions students often ask
What is the main idea behind count words in a sentence?
Track whether the scan is currently inside a word and increment the count only when a non-whitespace character starts a new word.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.