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
C# Exercise Example
// 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.");
}
}
}