Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2015-02-20
3
Medium Priority
?
245 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 1000 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 35

Assisted Solution

by:sarabande
sarabande earned 1000 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

670 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