Exercise
Mix And Sort Files
Objective
Create a program that reads the contents of two different files, merges them, and sorts them alphabetically. For example, if the files contain: "Dog Cat and Chair Table", the program should display: "Cat Chair Dog Table".
Write Your C# Exercise
C# Exercise Example
// 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
}
}