C# Program to Count Words in a String
string.Split(' ', StringSplitOptions.RemoveEmptyEntries) and then getting the length of the resulting array with .Length.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { string input = "Hello world from C#"; string[] words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries); int count = words.Length; Console.WriteLine(count); } }
Dry Run
Let's trace the input "Hello world from C#" through the code.
Input string
input = "Hello world from C#"
Split string by spaces
words = ["Hello", "world", "from", "C#"]
Count words
count = 4
Print result
Output: 4
| Step | Words Array |
|---|---|
| Split | ["Hello", "world", "from", "C#"] |
Why This Works
Step 1: Splitting the string
Using Split(' ', StringSplitOptions.RemoveEmptyEntries) breaks the string into parts separated by spaces and ignores empty parts caused by multiple spaces.
Step 2: Counting words
The length of the resulting array gives the number of words because each element is one word.
Alternative Approaches
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello world\nfrom C#"; string[] words = Regex.Split(input.Trim(), "\\s+"); Console.WriteLine(words.Length); } }
using System; class Program { static void Main() { string input = "Hello world from C#"; int count = 0; bool inWord = false; foreach (char c in input) { if (char.IsWhiteSpace(c)) { if (inWord) count++; inWord = false; } else { inWord = true; } } if (inWord) count++; Console.WriteLine(count); } }
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string scans each character once, so it takes linear time proportional to the string length.
Space Complexity
The split method creates an array of words, so space grows with the number of words.
Which Approach is Fastest?
Simple split with StringSplitOptions.RemoveEmptyEntries is fastest and easiest for normal cases; regex is slower but more flexible; manual counting uses less memory but is more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Split with RemoveEmptyEntries | O(n) | O(n) | Simple and common cases |
| Regex Split | O(n) | O(n) | Handling all whitespace types |
| Manual Counting | O(n) | O(1) | Custom word definitions, low memory |
StringSplitOptions.RemoveEmptyEntries to avoid counting empty strings as words.