Skip to main content

Word Count 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.

  
    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}.");
        }
    }