Skip to main content

Word Counter Script

The following C# script counts the number of words in a text file and outputs the total count. It has been used on several of the books on this wiki. If you have any questions or suggestions, you can join us on the Red Company Discord.

internal abstract class WordCounter
{
    private static void Main()
    {
        Console.WriteLine("Enter the file path to process:");
        string? inFileName = Console.ReadLine();

        int counter = 0;
        string delimiters = " ,.?!*”“:;";

        if (inFileName != null)
        {
            using StreamReader sr = new StreamReader(inFileName);
            while (!sr.EndOfStream)
            {
                string? line = sr.ReadLine()?.Trim();
                if (line is { Length: 0 }) 
                    continue;
    
                string[]? words = line?.Split(delimiters.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (words != null) 
                    counter += words.Length;
            }
        }

        Console.WriteLine($"The word count is {counter}.");
    }
}