C# program to count the number of words in a string

In C#, counting the number of words in a string can be accomplished using various approaches. The most common method involves iterating through each character and identifying word separators like spaces, tabs, and newlines.

Using Character-by-Character Iteration

This approach loops through the string and counts whitespace characters to determine word boundaries −

using System;

public class Demo {
   public static void Main() {
      int a = 0, myWord = 1;
      string str = "Hello World!";
      
      if (str.Length == 0) {
         myWord = 0;
      } else {
         while (a <= str.Length - 1) {
            if (str[a] == ' ' || str[a] == '<br>' || str[a] == '\t') {
               myWord++;
            }
            a++;
         }
      }
      
      Console.WriteLine("Number of words in the string = {0}", myWord);
   }
}

The output of the above code is −

Number of words in the string = 2

Using Split() Method

A more elegant approach uses the Split() method to divide the string into an array of words −

using System;

public class WordCounter {
   public static void Main() {
      string str = "Hello World! This is a test string.";
      
      string[] words = str.Split(new char[] {' ', '\t', '<br>'}, StringSplitOptions.RemoveEmptyEntries);
      int wordCount = words.Length;
      
      Console.WriteLine("Original string: " + str);
      Console.WriteLine("Number of words: " + wordCount);
      
      Console.WriteLine("Words found:");
      for (int i = 0; i < words.Length; i++) {
         Console.WriteLine((i + 1) + ". " + words[i]);
      }
   }
}

The output of the above code is −

Original string: Hello World! This is a test string.
Number of words: 7
Words found:
1. Hello
2. World!
3. This
4. is
5. a
6. test
7. string.

Using Regular Expressions

For more complex word counting scenarios, regular expressions provide flexible pattern matching −

using System;
using System.Text.RegularExpressions;

public class RegexWordCounter {
   public static void Main() {
      string str = "Hello,   World!    Multiple   spaces   here.";
      
      // Count words using regex pattern
      MatchCollection matches = Regex.Matches(str, @"\S+");
      int wordCount = matches.Count;
      
      Console.WriteLine("Original string: " + str);
      Console.WriteLine("Number of words: " + wordCount);
      
      Console.WriteLine("Words found:");
      int counter = 1;
      foreach (Match match in matches) {
         Console.WriteLine(counter + ". " + match.Value);
         counter++;
      }
   }
}

The output of the above code is −

Original string: Hello,   World!    Multiple   spaces   here.
Number of words: 5
Words found:
1. Hello,
2. World!
3. Multiple
4. spaces
5. here.

Comparison of Methods

Method Advantages Disadvantages
Character Iteration Simple logic, full control over separators More code, potential edge case handling
Split() Method Built-in functionality, handles multiple separators Creates array in memory
Regular Expressions Flexible patterns, handles complex scenarios Requires regex knowledge, performance overhead

Conclusion

Counting words in a string can be achieved through character iteration, the Split() method, or regular expressions. The Split() method is generally the most practical approach for simple word counting, while regular expressions offer flexibility for complex text processing scenarios.

Updated on: 2026-03-17T07:04:35+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements