Mezclar y ordenar archivos - Ejercicio de Programacion C# Sharp

En este ejercicio, se debe crear un programa que lea el contenido de dos archivos diferentes, los combine y los ordene alfabéticamente. El programa debe ser capaz de tomar el texto de ambos archivos, fusionarlos en una sola secuencia de palabras, y luego ordenarlas alfabéticamente antes de mostrar el resultado en la consola.

Por ejemplo, si los archivos contienen las palabras "Dog Cat and Chair Table", el programa debería mostrar el resultado "Cat Chair Dog Table", ordenando las palabras en orden alfabético.

Este ejercicio es una excelente manera de practicar la manipulación de archivos y cadenas de texto en C#, así como el uso de estructuras de datos como listas o arrays para almacenar temporalmente los datos leídos y realizar la ordenación.

 Categoría

Gestión Dinámica de Memoria

 Ejercicio

Mezclar Y Ordenar Archivos

 Objectivo

Cree un programa para leer el contenido de dos archivos diferentes y mostrarlo mezclado y ordenado alfabéticamente. Por ejemplo, si los archivos contienen: Dog Cat and Chair Table , debería mostrar Cat Chair Dog Table

 Ejemplo Ejercicio C#

 Copiar Código C#
// Importing necessary namespaces for file operations and basic collections
using System;  // Basic namespace for console input/output and fundamental operations
using System.Collections.Generic;  // For using collections like List
using System.IO;  // For file reading and writing operations

class Program
{
    // Function to read the contents of a file, split them into words, and return a sorted list
    static List ReadAndSortFile(string filePath)
    {
        // Check if the file exists before trying to read it
        if (File.Exists(filePath))  // If the file exists
        {
            // Read all lines from the file and split them into words
            string[] words = File.ReadAllText(filePath).Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);  // Read all text from the file and split by spaces and line breaks

            // Convert the array of words into a list and sort it alphabetically
            List sortedWords = new List(words);  // Create a list from the words array
            sortedWords.Sort();  // Sort the list alphabetically

            return sortedWords;  // Return the sorted list of words
        }
        else
        {
            Console.WriteLine($"The file {filePath} does not exist.");  // Print a message if the file does not exist
            return new List();  // Return an empty list if the file is not found
        }
    }

    // Main program method to read, merge, and sort the contents of two files
    static void Main(string[] args)
    {
        // Define the paths to the two input files
        string filePath1 = "file1.txt";  // Path for the first input file
        string filePath2 = "file2.txt";  // Path for the second input file

        // Read and sort the contents of both files
        List sortedWords1 = ReadAndSortFile(filePath1);  // Read and sort the first file
        List sortedWords2 = ReadAndSortFile(filePath2);  // Read and sort the second file

        // Merge the two sorted lists
        sortedWords1.AddRange(sortedWords2);  // Add the words from the second file to the first

        // Sort the merged list alphabetically
        sortedWords1.Sort();  // Sort the merged list alphabetically

        // Display the sorted words in the console
        Console.WriteLine("Merged and sorted words:");
        foreach (string word in sortedWords1)  // Iterate through the sorted words
        {
            Console.Write(word + " ");  // Display each word followed by a space
        }

        Console.WriteLine();  // Add a line break after the output
    }
}

 Salida

If the content of file1.txt is:
apple orange banana

And the content of file2.txt is:
grape kiwi apple

The output in the console would be:
Merged and sorted words:
apple apple banana grape kiwi orange 

 Comparte este Ejercicio C# Sharp

 Más Ejercicios de Programacion C# Sharp de Gestión Dinámica de Memoria

¡Explora nuestro conjunto de ejercicios de programación C# Sharp! Estos ejercicios, diseñados específicamente para principiantes, te ayudarán a desarrollar una sólida comprensión de los conceptos básicos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte de manera gradual a medida que adquieres confianza en la codificación en C#.

  •  ArrayList de puntos

    En este ejercicio, debes crear una estructura llamada "Point3D" para representar un punto en un espacio tridimensional con las coordenadas X, Y y Z. La estructura debe permi...

  •  Buscar en archivo

    En este ejercicio, debes crear un programa que lea el contenido de un archivo de texto, guarde ese contenido en un ArrayList y permita al usuario ingresar oraciones p...

  •  Implementación de una cola usando una matriz

    En este ejercicio, deberás implementar una cola (queue) en C#. Una cola es una estructura de datos que sigue el principio FIFO (First In, First Out), es decir,...

  •  Implementar una pila usando una matriz

    En este ejercicio, deberás implementar una pila (stack) en C#. Una pila es una estructura de datos que sigue el principio LIFO (Last In, First Out), es decir, ...

  •  Colecciones de colas

    En este ejercicio, deberás crear una cola de cadenas utilizando la clase Queue que ya existe en la plataforma DotNet. La clase Queue es una implementación de l...

  •  Notación Polish inversa de pila de cola

    En este ejercicio, deberás crear un programa que lea una expresión en Notación Polaca Inversa (RPN, por sus siglas en inglés) desde un archivo de texto, como por ejemplo: