Ejercicio
Contar Letras En Un Archivo
Objectivo
Cree un programa para contar la cantidad de veces que un determinado carácter está dentro de un archivo (de cualquier tipo).
El archivo y la carta se pueden pedir al usuario o pasar como parámetros:
ejemplo de recuento.txt un
Debe mostrar en pantalla la cantidad de letras encontradas.
(puede elegir cualquier forma de interactuar con el usuario, mostrando la ayuda adecuada)
Ejemplo Ejercicio C#
Mostrar Código C#
// 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.");
}
}
}
Salida
Enter the file path: sample.txt
Enter the character to count: a
The character 'a' appears 10 times in the file.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp