Text Replacer - C# Programming Exercise

In this exercise of C#, you need to create a program to replace words in a text file, saving the result into a new file. The program should take as parameters the file name, the word to search for, and the word to replace it with. For example, if the user runs the command "replace file.txt hello goodbye", the new file will be named "file.txt.out" and will contain all appearances of "hello" replaced by "goodbye". This exercise is perfect for learning how to work with text files and manipulate strings within those files. It also helps programmers get familiar with handling input and output parameters, which is an important skill when creating text processing tools.

Through this exercise, programmers will learn how to open, read, modify, and save files, enabling them to create useful applications for managing text efficiently.

 Category

File Management

 Exercise

Text Replacer

 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

// 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.");
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Count letters in a file

    In this exercise of C#, you need to create a program to count how many times a specific character appears inside a file of any kind. The file and the letter to search...

  •  Reading a binary file (1: BMP)

    In this exercise of C#, you need to create a program that checks if a BMP image file seems to be correct. The program must verify if the first two bytes of the file ...

  •  Writing to a binary file

    In this exercise of C#, you need to create a program that asks the user for their name, age (as a byte), and the year they were born (as an int), and st...

  •  C# to Java

    In this exercise of C#, you need to create a basic C# to Java translator. The program should accept C# source files and generate an equivalent ...

  •  Invert a text file

    This C# exercise aims to teach how to manipulate text files and reverse their content using basic programming structures. In this exercise, you need to create ...

  •  Reading a binay file (2 - GIF)

    This C# exercise aims to teach how to check the validity of a GIF image file. In this exercise, you need to create a program that reads the first four bytes of...