Connecting Tech Pros Worldwide Forums | Help | Site Map

string occurences

Member
 
Join Date: Oct 2006
Location: California, USA
Posts: 45
#1: Dec 8 '06
Hi,

im doing this question:
Replace all the occurrences of a string in a file and report number of replacements.

I did the first part of the question, but im having problems with the second part, i which i have to report the number of replacements.

this is the code that i did so far:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <conio.h>
  3. #include <fstream>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     string whole_file, str;
  10.     ifstream in ("file.txt");
  11.     while (!in.eof())
  12.     {
  13.           std::getline(in,str,'\n');
  14.           whole_file = whole_file + str + "\n";
  15.  
  16.     }
  17.  
  18.   int pos = 0;
  19.  
  20.   while (pos!=-1 && pos<whole_file.length())
  21.   {
  22.     pos = whole_file.find ("money", 0);
  23.     if (pos!=-1)
  24.     {
  25.       cout<<whole_file.replace(pos, 5, "university", 10);
  26. }
  27. }
  28. cout<<whole_file;
  29.  
  30. getch();
  31. return 0;
  32.  
  33. }

Thanks..... all help on how i can solve the second part of the question will be very much appreaciated.

Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#2: Dec 8 '06

re: string occurences


all you need is a counter which you increment when you replace a string, e.g.
Expand|Select|Wrap|Line Numbers
  1.   int pos = 0, counter=0;
  2.  
  3.   while (pos!=-1 && pos<whole_file.length())
  4.   {
  5.     pos = whole_file.find ("money", 0);
  6.     if (pos!=-1)
  7.     {
  8.       cout<<whole_file.replace(pos, 5, "university", 10);
  9.       counter++;
  10. }
  11. }
  12.  
Member
 
Join Date: Oct 2006
Location: California, USA
Posts: 45
#3: Dec 8 '06

re: string occurences


Quote:

Originally Posted by horace1

all you need is a counter which you increment when you replace a string, e.g.

Expand|Select|Wrap|Line Numbers
  1.   int pos = 0, counter=0;
  2.  
  3.   while (pos!=-1 && pos<whole_file.length())
  4.   {
  5.     pos = whole_file.find ("money", 0);
  6.     if (pos!=-1)
  7.     {
  8.       cout<<whole_file.replace(pos, 5, "university", 10);
  9.       counter++;
  10. }
  11. }
  12.  


Thanks soooo much for your help horace!! :D
Reply