Count Letters In A File - C# Programming Exercise

In this exercise of C#, you need to create a program to count how many times a specific character appears inside a file of any kind. The file and the letter to search for can be asked from the user or passed as parameters. For example, if the user runs the command "count example.txt a", the program should display the number of times the letter "a" appears in the file "example.txt". This exercise is great for learning how to work with text files and process their contents efficiently by searching for specific characters. It also teaches how to interact with the user flexibly, either by prompting for input via a menu or receiving parameters directly.

Through this exercise, programmers will learn how to read files, count characters, and display the results clearly, enabling them to create useful programs to analyze and process text data.

 Category

File Management

 Exercise

Count Letters In A File

 Objective

Create a program to count the amount of times that a certain character is inside a file (of any kind).

The file and the letter can be asked to the user or passed as parameters:

count example.txt a

It must display in screen the amount of letters found.

(you can choose any way to interact with the user, showing the proper help)

 Write Your C# Exercise

// Importing necessary namespaces for file handling
using System;
using System.IO;

public class CharacterCounter
{
    // Method to count occurrences of a character in a file
    public static int CountCharacterInFile(string filePath, char character)
    {
        // Counter to keep track of occurrences of the specified character
        int count = 0;

        // Using StreamReader to read the file
        using (StreamReader reader = new StreamReader(filePath))
        {
            // Looping through each character in the file
            while (!reader.EndOfStream)
            {
                // Reading a character from the file
                char currentChar = (char)reader.Read();

                // Incrementing the counter if the character matches
                if (currentChar == character)
                {
                    count++;
                }
            }
        }

        // Returning the total count of the specified character
        return count;
    }
}

// Auxiliary class with Main method for testing the functionality
public class Program
{
    public static void Main(string[] args)
    {
        // Variables to store the file path and character
        string filePath;
        char character;

        // Checking if both file path and character are provided as arguments
        if (args.Length == 2)
        {
            // Assigning the arguments to variables for clarity
            filePath = args[0];
            character = args[1][0];
        }
        else
        {
            // Prompting the user for the file path if not provided as an argument
            Console.Write("Enter the file path: ");
            filePath = Console.ReadLine();

            // Prompting the user for the character if not provided as an argument
            Console.Write("Enter the character to count: ");
            character = Console.ReadKey().KeyChar;
            Console.WriteLine();
        }

        // Checking if the specified file exists
        if (File.Exists(filePath))
        {
            // Calling the CountCharacterInFile method to get the count of the character
            int count = CharacterCounter.CountCharacterInFile(filePath, character);

            // Displaying the total count to the user
            Console.WriteLine($"The character '{character}' appears {count} times in the file.");
        }
        else
        {
            // Displaying an error message if the file does not exist
            Console.WriteLine("The specified file does not exist.");
        }
    }
}

 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#.

  •  Reading a binary file (1: BMP)

    In this exercise of C#, you need to create a program that checks if a BMP image file seems to be correct. The program must verify if the first two bytes of the file ...

  •  Writing to a binary file

    In this exercise of C#, you need to create a program that asks the user for their name, age (as a byte), and the year they were born (as an int), and st...

  •  C# to Java

    In this exercise of C#, you need to create a basic C# to Java translator. The program should accept C# source files and generate an equivalent ...

  •  Invert a text file

    This C# exercise aims to teach how to manipulate text files and reverse their content using basic programming structures. In this exercise, you need to create ...

  •  Reading a binay file (2 - GIF)

    This C# exercise aims to teach how to check the validity of a GIF image file. In this exercise, you need to create a program that reads the first four bytes of...

  •  Friends database, using files

    This C# exercise aims to expand a friends database by allowing data to be loaded from a file at the beginning of each session and saved to...