0
0
CsharpProgramBeginner · 2 min read

C# Program to Count Words in a String

You can count words in a string in C# by splitting the string with string.Split(' ', StringSplitOptions.RemoveEmptyEntries) and then getting the length of the resulting array with .Length.
📋

Examples

InputHello world
Output2
Input This is a simple test string.
Output6
Input
Output0
🧠

How to Think About It

To count words, think of words as groups of characters separated by spaces. We split the string by spaces, ignore empty parts caused by extra spaces, and count how many parts remain.
📐

Algorithm

1
Get the input string.
2
Split the string by spaces, ignoring empty entries.
3
Count the number of parts in the split result.
4
Return or print the count.
💻

Code

csharp
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);
    }
}
Output
4
🔍

Dry Run

Let's trace the input "Hello world from C#" through the code.

1

Input string

input = "Hello world from C#"

2

Split string by spaces

words = ["Hello", "world", "from", "C#"]

3

Count words

count = 4

4

Print result

Output: 4

StepWords 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 Regex to split by any whitespace
csharp
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);
    }
}
This handles all whitespace like tabs and new lines, but requires importing Regex and may be slower.
Counting words by iterating characters
csharp
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);
    }
}
This method counts words manually without splitting, useful for custom definitions but more complex.

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.

ApproachTimeSpaceBest For
Split with RemoveEmptyEntriesO(n)O(n)Simple and common cases
Regex SplitO(n)O(n)Handling all whitespace types
Manual CountingO(n)O(1)Custom word definitions, low memory
💡
Use StringSplitOptions.RemoveEmptyEntries to avoid counting empty strings as words.
⚠️
Beginners often forget to remove empty entries, causing wrong word counts when multiple spaces appear.