Exercise
Mix and sort files
Objetive
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".
Example Code
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static List ReadAndSortFile(string filePath)
{
if (File.Exists(filePath))
{
string[] words = File.ReadAllText(filePath).Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
List sortedWords = new List(words);
sortedWords.Sort();
return sortedWords;
}
else
{
Console.WriteLine($"The file {filePath} does not exist.");
return new List();
}
}
static void Main(string[] args)
{
string filePath1 = "file1.txt";
string filePath2 = "file2.txt";
List sortedWords1 = ReadAndSortFile(filePath1);
List sortedWords2 = ReadAndSortFile(filePath2);
sortedWords1.AddRange(sortedWords2);
sortedWords1.Sort();
Console.WriteLine("Merged and sorted words:");
foreach (string word in sortedWords1)
{
Console.Write(word + " ");
}
Console.WriteLine();
}
}