string occurences

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • outofmymind
    New Member
    • Oct 2006
    • 45

    string occurences

    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:

    Code:
    #include <iostream>
    #include <conio.h>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
        string whole_file, str;
        ifstream in ("file.txt");
        while (!in.eof())
        {
              std::getline(in,str,'\n');
              whole_file = whole_file + str + "\n";
              
        }
        
      int pos = 0;
      
      while (pos!=-1 && pos<whole_file.length())
      {
        pos = whole_file.find ("money", 0);
        if (pos!=-1)
        {
          cout<<whole_file.replace(pos, 5, "university", 10);
    }
    }
    cout<<whole_file;
    
    getch();
    return 0;
    
    }

    Thanks..... all help on how i can solve the second part of the question will be very much appreaciated.
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    all you need is a counter which you increment when you replace a string, e.g.
    Code:
      int pos = 0, counter=0;
      
      while (pos!=-1 && pos<whole_file.length())
      {
        pos = whole_file.find ("money", 0);
        if (pos!=-1)
        {
          cout<<whole_file.replace(pos, 5, "university", 10);
          counter++;
    }
    }

    Comment

    • outofmymind
      New Member
      • Oct 2006
      • 45

      #3
      Originally posted by horace1
      all you need is a counter which you increment when you replace a string, e.g.
      Code:
        int pos = 0, counter=0;
        
        while (pos!=-1 && pos<whole_file.length())
        {
          pos = whole_file.find ("money", 0);
          if (pos!=-1)
          {
            cout<<whole_file.replace(pos, 5, "university", 10);
            counter++;
      }
      }

      Thanks soooo much for your help horace!! :D

      Comment

      Working...