Ejercicio
Cambiador De Texto
Objectivo
Cree un programa para reemplazar palabras en un archivo de texto, guardando el resultado en un nuevo archivo.
El archivo, la palabra a buscar y la palabra para reemplazarlo deben darse como parámetros:
reemplazar archivo.txt hola adiós
El nuevo archivo se llamaría "file.txt.out" y contendría todas las apariencias de "hello" reemplazadas por "goodbye".
Ejemplo Ejercicio C#
Mostrar Código C#
// 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.");
}
}
}
Salida
replace sample.txt oldWord newWord
sample.txt is the file containing:
This is an oldWord.
The oldWord needs to be replaced.
Another line with the word oldWord.
Content of sample.txt.out:
This is a newWord.
The newWord needs to be replaced.
Another line with the word newWord.
The modified file has been saved as sample.txt.out
If the file does not exist: The specified file does not exist.
If incorrect arguments are provided:
Usage: replace file searchWord replaceWord
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp