Objective
Create a program to replace words in a text file, saving the result into a new file.
The file, the word to search and word to replace it with must be given as parameters:
replace file.txt hello goodbye
The new file would be named "file.txt.out" and contain all the appearances of "hello" replaced by "goodbye".
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for file handling
using System;
using System.IO;
public class TextReplacer
{
// Method to replace words in a text file and save the result in a new file
public static void ReplaceWords(string filePath, string searchWord, string replaceWord)
{
// Defining the output file name by appending ".out" to the original file name
string outputFilePath = filePath + ".out";
// Using StreamReader to read the input file
using (StreamReader reader = new StreamReader(filePath))
// Using StreamWriter to write to the output file
using (StreamWriter writer = new StreamWriter(outputFilePath))
{
// Looping through each line in the input file
while (!reader.EndOfStream)
{
// Reading a line from the input file
string line = reader.ReadLine();
// Replacing all occurrences of the search word with the replace word
string modifiedLine = line.Replace(searchWord, replaceWord);
// Writing the modified line to the output file
writer.WriteLine(modifiedLine);
}
}
// Displaying a message indicating where the output has been saved
Console.WriteLine($"The modified file has been saved as {outputFilePath}");
}
}
// Auxiliary class with Main method for testing the functionality
public class Program
{
public static void Main(string[] args)
{
// Checking if the correct number of arguments were provided
if (args.Length != 3)
{
// Displaying usage information if the arguments are incorrect
Console.WriteLine("Usage: replace ");
return;
}
// Assigning arguments to variables for clarity
string filePath = args[0];
string searchWord = args[1];
string replaceWord = args[2];
// Checking if the specified file exists
if (File.Exists(filePath))
{
// Calling the ReplaceWords method to perform the replacement
TextReplacer.ReplaceWords(filePath, searchWord, replaceWord);
}
else
{
// Displaying an error message if the file does not exist
Console.WriteLine("The specified file does not exist.");
}
}
}