Solved

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

Posted on 2015-02-20
3
226 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
Comment Utility
#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 32

Assisted Solution

by:sarabande
sarabande earned 250 total points
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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.

743 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

17 Experts available now in Live!

Get 1:1 Help Now