Search and Replace strings in text files in C++

In this article, we will two different approaches to search and replace a string in a text file in C++.

Table Of Contents

Approach 1: Read whole file, and replace text

This program reads the contents of the text file into a string, performs the search and replace operation on the string, and then writes the modified string back to the file.

Algorithm

  1. Open the input file for reading.
  2. Check if the file was opened successfully. If not, print an error message and exit the program.
  3. Read the contents of the file into a string.
  4. Close the file.
  5. Perform the search and replace operation on the string.
  6. Open the input file for writing.
  7. Check if the file was opened successfully. If not, print an error message and exit the program.
  8. Write the modified string back to the file.
  9. Close the file.

Program

Advertisements
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
  // Open the file for reading
  ifstream fin("input.txt");

  // Check if the file was opened successfully
  if (!fin) 
  {
    cerr << "Error opening file" << endl;
    return 1;
  }

  // Read the contents of the file into a string
  string text(
          (istreambuf_iterator<char>(fin)),
          istreambuf_iterator<char>());

  fin.close();

  // Perform the search and replace operation on the string
  string search = "old";
  string replace = "new";
  size_t pos = 0;

  while ((pos = text.find(search, pos)) != string::npos) 
  {
    text.replace(pos, search.length(), replace);
    pos += replace.length();
  }

  // Open the file for writing
  ofstream fout("input.txt", ios::trunc);

  // Check if the file was opened successfully
  if (!fout) 
  {
    cerr << "Error opening file" << endl;
    return 1;
  }

  // Write the modified string back to the file
  fout << text;
  fout.close();

  return 0;
}

Methods and classes used:

  1. The input file is opened for reading using the ifstream class.
  2. The file is checked to see if it was opened successfully using the if (!fin) condition. If the file was not opened successfully, a message is printed to the console using cerr and the program exits with a non-zero return value.
  3. The contents of the file are read into a string using the string class’s constructor:
    Syntax : string text((istreambuf_iterator(fin)), istreambuf_iterator());
    This constructor reads the contents of the file from the input stream (fin) into the string. The istreambuf_iterator class is used to iterate through the characters in the stream.
  4. The file is closed using the close() method of the ifstream class.
  5. The search and replace operation is performed on the string using the find() and replace() methods of the string class. The find() method searches for a substring within the string and returns the position of the first occurrence of the substring. If the substring is not found, string::npos is returned. The replace() method replaces a substring with another string. The loop continues until the search string is not found in the text.
  6. The input file is opened for writing using the ofstream class. The ios::trunc flag is used to truncate the file to zero length before writing to it.
  7. The file is checked to see if it was opened successfully using the if (!fout) condition. If the file was not opened successfully, a message is printed to the console using cerr and the program exits with a non-zero return value.
  8. The modified string is written to the file using the ofstream object and the << operator.
  9. The file is closed using the close() method of the ofstream class.

Time Complexity – O(N + NM)

  • N is the length of the input string and M is the length of the old substring

The time complexity of the program depends on the size of the input file and the number of times the search string appears in the file. The program reads the entire contents of the file into a string, so the time complexity of this operation is O(N). The search and replace operation is performed using a loop that continues until the search string is not found in the text. The find() method of the string class has a time complexity of O(M*N). Therefore, the time complexity of the search and replace operation is O(NM). The program writes the modified string back to the file, which has a time complexity of O(N). Therefore, the overall time complexity of the program is O(N + NM).

Note

This is the worst-case time complexity, which occurs when the search string appears in every character of the text. In the best case, when the search string does not appear in the text at all, the time complexity is O(N).

Approach 2: Read file line by line, and modify in parallel

This program reads the text file line by line, performs the search and replace operation on each line, and then writes the modified line back to the file.

Algorithm

  1. Open the input file for reading and writing.
  2. Check if the file was opened successfully. If not, print an error message and exit the program.
  3. Read each line of the file into a string.
  4. Perform the search and replace operation on the string.
  5. Go back to the beginning of the line in the file and write the modified line.
  6. Repeat steps 3-5 until all lines of the file have been processed.
  7. Close the file.

Program

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() 
{
  // Open the file for reading and writing
  fstream fio("input.txt", ios::in | ios::out);

  // Check if the file was opened successfully
  if (!fio) 
  {
    cerr << "Error opening file" << endl;
    return 1;
  }

  // Perform the search and replace operation on each line of the file
  string search = "old";
  string replace = "new";
  string line;
  while (getline(fio, line)) 
  {
    size_t pos = 0;
    while ((pos = line.find(search, pos)) != string::npos) 
    {
      line.replace(pos, search.length(), replace);
      pos += replace.length();
    }

    // Go back to the beginning of the line and write the modified line
    fio.seekp(-line.length() - 1, ios::cur);
    fio << line <<endl;
  }

  fio.close();

  return 0;
}

Methods and classes used:

  1. The input file is opened for reading and writing using the fstream class.
  2. The file is checked to see if it was opened successfully using the if (!fio) condition. If the file was not opened successfully, a message is printed to the console using cerr and the program exits with a non-zero return value.
  3. The getline() function is used to read each line of the file into a string. The loop continues until there are no more lines to read.
  4. The search and replace operation is performed on the string using the find() and replace() methods of the string class. The find() method searches for a substring within the string and returns the position of the first occurrence of the substring. If the substring is not found, string::npos is returned. The replace() method replaces a substring with another string. The loop continues until the search string is not found in the text.
  5. The file position is moved to the beginning of the current line using the seekp() method of the fstream class. The modified line is then written to the file using the fstream object and the << operator.
  6. Steps 3-5 are repeated until all lines of the file have been processed.
  7. The file is closed using the close() method of the fstream class.

Time Complexity – O(N + NM)

N is the length of the input string and M is the length of the old substring
The time complexity of the program depends on the size of the input file and the number of times the search string appears in the file. The program reads the file line by line, so the time complexity of this operation is O(N), where n is the number of lines in the file. The search and replace operation is performed using a loop that continues until the search string is not found in the text. The find() method of the string class has a time complexity of O(M*N). Therefore, the time complexity of the search and replace operation is O(NM). The program writes the modified line back to the file, which has a time complexity of O(M), where M is the length of the modified line. Therefore, the overall time complexity of the program is O(N + NM).

Note

Note that this is the worst-case time complexity, which occurs when the search string appears in every line of the file. In the best case, when the search string does not appear in any lines of the file, the time complexity is O(N).

Summary

In this article, we learned how to search for a string and replace it with some other string in a text file using C++.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top