By Rati Gupta
This C++ program counts all the occurrences of a specific word in a text file and finds their positions. Then, replaces all of them with another word.
Example
file.txt:- A thesis statement identifies the topic being discussed.
Input:-
Enter your file name: file.txt
Enter the word you want to replace: the
Enter the new word to replace the old one: your
Output:-
Word is found at : 30
Total count: 1 time(s)
Modified file:-
file.txt:- A thesis statement identifies your topic being discussed.
This program uses the case-sensitive approach to find the word.
Approach:
1. Open the file given by the user.
2. Create a file stream variable to store the content of the file.
3. Extract the content from the file stream into a string variable.
4. Find the starting position of the word using the find() function.
5. Replace the word with another word using replace() function.
6. Repeat steps 4 and 5 via the while loop till the end has reached.
7. Write the modified string to the file.
#include
#include
#include
#include
using namespace std;
int main()
{
int i=0,cpos;
string new_word,filename,str,old;
stringstream text; //Creating a string stream to store the data of a file
fstream file_ob; //creating an input/output stream
cout<<"Enter your file name:";
cin>>filename;
cout<<endl<<"Enter the word you want to replace: ";
cin>>old;
cout<<"Enter the new word to replace old one: ";
cin>>new_word;
cout<<"Word is found at: ";
file_ob.open(filename.c_str(), ios::in|ios::out|ios::binary); //opening a file
text<<file_ob.rdbuf(); //now the content of file is present in text.str()
str=text.str();
size_t pos = str.find(old); //finding first occurence of substring
while( pos != std::string::npos) // Repeat till the end is reached
{
if(pos==0)
cpos=pos+old.size();
else
cpos=pos-1;
if((isspace(str[cpos])||ispunct(str[cpos])) && (isspace(str[pos+old.size()]))||ispunct(str[pos+old.size()]) //Checking whether found substring is a word or not
{
cout<<pos<<" ";
str.replace(pos,old.length(),new_word);
i++;
}
pos=str.find(old, pos + old.size()+1); // Get the next occurrence from the current position
}
if(i==0)
cout<<"No position";
cout<<"."<<endl;
cout<<"Total count:"<<i<<" time(s)"<<endl;
if(i>0)
cout<<" *********Your file has been modified**********";
ofstream write_file(filename.c_str(), ios::binary);
write_file <<str;
file_ob.clear();
file_ob.close();
return 0;
}
Output:-

Submitted by Rati Gupta (rati123)
Download packets of source code on Coders Packet
Comments