Objective
Create a program to censor text files. It should read a text file and dump its results to a new text file, replacing certain words with "[CENSORED]". The words to censor will be stored in a second data file, a text file that will contain one word per line.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System;
using System.Collections.Generic;
using System.IO;
class TextCensorship
{
// Main method where the program execution begins
static void Main()
{
// Path to the input text file that will be censored
string inputFilePath = "input.txt";
// Path to the file containing the words to be censored (one word per line)
string censorFilePath = "censorship_list.txt";
// Path to the output file where the censored text will be written
string outputFilePath = "output.txt";
// Call the CensorText method to process the file and censor the words
CensorText(inputFilePath, censorFilePath, outputFilePath);
}
// Method to read the input file, censor words, and write the result to a new file
static void CensorText(string inputFilePath, string censorFilePath, string outputFilePath)
{
try
{
// Read the words to censor from the censorship list file
HashSet wordsToCensor = new HashSet(File.ReadAllLines(censorFilePath));
// Read the input text file into a string
string inputText = File.ReadAllText(inputFilePath);
// Loop through each word to censor and replace it with "[CENSORED]"
foreach (var word in wordsToCensor)
{
// Replace all occurrences of the word (case-insensitive)
inputText = inputText.Replace(word, "[CENSORED]", StringComparison.OrdinalIgnoreCase);
}
// Write the censored text to the output file
File.WriteAllText(outputFilePath, inputText);
Console.WriteLine("Text has been censored and written to the output file.");
}
catch (Exception ex)
{
// Catch any errors (e.g., file not found or read/write issues) and display an error message
Console.WriteLine("Error: " + ex.Message);
}
}
}