Solved

File parse code to search and replace a string of text.

Posted on 2015-02-20
3
228 Views
Last Modified: 2015-02-21
I am looking for some C or C++ code that would parse a text file, and replace all occurrences of a string with another string.

So if I have a text file with this text : Mary had a little lamb who's name was Mary Anne.

And I want to replace "Mary" with "Terry",  how can I do that in C++. My file might have up to 1000 lines of text in it. The end result would be Terry had a little lamb who's name was Terry Anne.
0
Comment
Question by:brgdotnet
  • 2
3 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 250 total points
ID: 40622607
#include <iostream>
#include <string>
using namespace std;
string substitute(string str,string find,string replace){
  for( size_t i=0;(i = str.find(find,i))!=string::npos;i+=replace.length() ){
      str.replace(i,find.length(),replace);
  }
  return str;
}
int main ()
{
 string str;
 while( cin.good() ){
   getline(cin,str);
   cout << substitute(str,"Mary","Terry") << endl;
 }
 return 0;
}

Open in new window

0
 
LVL 33

Assisted Solution

by:sarabande
sarabande earned 250 total points
ID: 40622875
the following program would read all text of a file to memory and replace Mary by Terry. finally the same file was written again.

#include <sys/stat.h>
#include <errno.h>
#include <fstream>
#include <string>

int main(int nargs, char * szargs[])
{
       struct stat fileinfo = { 0 };
       if (nargs < 2 || stat(szargs[1], &fileinfo) != 0) return -1;  // no commandline argument or file doesn't exist
       std::ifstream ifstext(szargs[1], std::ios::binary | std::ios::in);
       std::string buf(fileinfo.st_size, '\0');
       if (!ifstext.read(&buf[0], fileinfo.st_size)) return errno;
       ifstext.close();
       size_t pos, lpos = 0;
       while ((pos = buf.find("Mary", lpos)) != std::string::npos)
       {
              buf.replace(pos, sizeof("Mary")-1, "Terry");
              lpos = pos+1;
       }
       std::ofstream ofstext(szargs[1], std::ios::binary | std::ios::out);
       if (!ofstext.write(buf.c_str(), buf.length())) return errno;
       ofstext.close();
       return 0;
}

Open in new window


you would call the program at the commmandline passing the filepath as argument.

note, the while loop is equivalent to the for loop ozo has used in the substitute function.

you may mix both codes by opening the file in text mode for read, then read line by line using std::getline from file, for each line do the substitution and add the modified line into a std::vector<std::string> container. finally close the file and open it again for write. write all the lines from vector back to the output file (note, you have to add a linefeed character to each line).

Sara
0
 
LVL 84

Expert Comment

by:ozo
ID: 40623022
Note that the while loop would not be equivalent to the for loop if you wanted to replace "Mary" with "Mary, Mary, Quite Contrary"
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
FMX StringGrid1->Canvas->FillRect Problem 3 126
Find Visual Studio Tools 2 92
Need some help with Microsoft Visual Studio C++ 2003 5 51
Raspberry Pi 3 to send text message 9 65
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

947 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now