Count Words - C# Programming Exercise

This C# exercise involves creating a program to count the number of words stored in a text file. The program should read the content of a text file, process it, and count how many words it contains, then display the result to the user. This exercise is ideal for learning about text file processing in C#, as well as how to manipulate strings and perform counting operations.

The program should be able to open a text file, read it line by line, and split each line into words using a separator such as a space or line break. It should then count how many words are found in the file and display that count at the end. This exercise will help you get familiar with file reading functions in C# and string processing, which is useful in many applications.

Additionally, it is important that the .cs file includes a comment with your name to ensure that the code is identified as yours. This exercise is essential for understanding text file handling and string manipulation in C#, providing a solid foundation for text processing tasks in more complex projects.

 Category

File Management

 Exercise

Count Words

 Objective

Create a C# program to count the amount of words stored in a text file

 Write Your C# Exercise

// Import the System namespace for basic functionality
using System;  

// Import the IO namespace for file handling
using System.IO;  

// Create the class to count words in the text file
class WordCounter
{
    // Main method where the program starts
    static void Main(string[] args)
    {
        // Ask the user for the path of the text file
        Console.WriteLine("Enter the path of the text file:");  

        // Get the file path from the user
        string filePath = Console.ReadLine();  

        // Start of try block to handle any file or reading errors
        try
        {
            // Read the content of the file
            string content = File.ReadAllText(filePath);  

            // Count the number of words in the file by splitting the content into words
            int wordCount = CountWords(content);  

            // Display the result to the user
            Console.WriteLine("The number of words in the file is: " + wordCount);  
        }
        catch (Exception ex)  // Catch any exceptions that may occur during file reading
        {
            // Print the exception message if an error occurs
            Console.WriteLine("An error occurred: " + ex.Message);  
        }
    }

    // Method to count the number of words in a string
    private static int CountWords(string content)
    {
        // Split the content by spaces, tabs, newlines, etc. to get an array of words
        string[] words = content.Split(new char[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);  

        // Return the length of the array, which is the number of words
        return words.Length;  
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  BMP width and height, BinaryReader

    This C# exercise involves creating a program to display the width and height of a BMP file using a BinaryReader. The program should read the BMP file header an...

  •  TXT to HTML translator

    This C# exercise involves creating a "Text to HTML converter". The program should read a source text file and create an HTML file from its contents. The destination f...

  •  Invert binary file V2

    This C# exercise involves creating a program to "invert" a file using a FileStream. The program should create a file with the same name as the original file, b...

  •  BMP width & height, FileStream

    This C# exercise involves creating a program that reads a BMP file using a FileStream and displays its width and height. The BMP format has a spe...

  •  File copier

    This C# exercise involves creating a program that copies a source file to a destination file using a FileStream and a block size of 512 KB. The program should ...

  •  MP3 reader

    This C# exercise is about the ID3 specifications, which apply to any file or audiovisual container, but are primarily used with audio containers. There are three comp...