Thread: replace() algorithm

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    replace() algorithm

    Shouldnt "replace()" find and replace every instance of str with str2 in the vector?
    So why does it replace only one "tom" on one line and not several?
    I guess it has something to do with getline().
    But in the example with an "int" it finds several instances of the same number in one line.
    http://www.cplusplus.com/reference/a...m/replace.html
    So i dont understand whats the problem. Thanks!

    Code:
    int main()
    {
         vector<string> myvector;
         vector<string>::iterator it;
         string str  = "tom";
         string str2 = "Tom";
         string str3;
         ifstream file ("1.txt");
         
         while (getline(file, str3))
         {
               myvector.push_back(str3);
         }    
         
         replace(myvector.begin(), myvector.end(), str, str2);
         
         for (it = myvector.begin(); it != myvector.end(); it++)
              cout << *it << "\n";
    
     file.close();
     system("pause");
    }

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    What does the input file look like? If there is anything else in a given line from the file other than "tom" then it will not find a match and therefore not do the replacement. For example, there could be a space at the end, i.e. "tom ", in the file so the replace function won't find a match comparing with "tom". Or... Are you saying that there is a single line in the file that has "tom tom tom" and you want that to become "Tom Tom Tom"? If that's the case then what you have won't work.

    Quote Originally Posted by Ducky
    But in the example with an "int" it finds several instances of the same number in one line.
    No, you may be thinking of this wrong. Don't look at that example and say "in one line". It's not "one line" just because all the numbers in the array are declared in a single line. You're interpreting/looking at that wrong. It is more like saying "in one container". The array is a container and the replace function iterates over that container element by element and does a compare/replace if necessary. Thus in that case, it iterates integer by integer in through array and tries to match those individual elements and do a replace if needed.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    The algorithm replace(begin, end, old_val, new_val), what you are calling, compares the whole sequence (in this case the whole string) with the old value. The only way it will work is if the whole string equals old_val. So, only a line with "tom" on it with nothing else will work. See here:

    Code:
    #include <iostream>
    #include <vector> 
    #include <algorithm> 
    
    using namespace std ; 
    
    int main()
    {
    	vector<string> myvector;
    	vector<string>::iterator it;
    	string str  = "tom";
    	string str2 = "Tom";
    	
    	myvector.push_back("tom");   // works 
    	myvector.push_back("bob");
    	myvector.push_back("tom ");  // won't work - has a blank 
    	myvector.push_back("tom");   // works 
    	// nothing else below works..
    	myvector.push_back("Dear tom, ");
    	myvector.push_back(" ");
    	myvector.push_back("How are you today tom?");
    	myvector.push_back("Do you like tomatoes?");
    	myvector.push_back("My tomtom broke, and now I have to buy a drum.");
    	myvector.push_back("I like won tom soup.  I mean won ton.");
    	myvector.push_back("Later, tom jr. ");
    	
    	replace(myvector.begin(), myvector.end(), str, str2);
    	
    	for (it = myvector.begin(); it != myvector.end(); it++)
    	cout << *it << "\n";
    }
    Tom. I mean Todd.

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thank you guys, i get it now.
    So if i guess right there is no function or algorithm alone to find a piece of string in another string and replace it.
    So i guess i need at least two.
    I thought about to use string::find() and replace() algorithm.
    1.getline()
    2.find()
    3.replace()

    My only concern is that find only returns the first occurrence found in the string
    and lets alone the rest.
    In a string "tom tom tom" it will only return the first "tom".
    Is there a function that returns every instance found in a string or have to write one?
    Last edited by Ducky; 01-25-2008 at 11:28 AM.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Is there a function that returns every instance found in a string or have to write one?
    You would normally do that in a loop using the previous location as a starting point for the next search.

    You could also make a function object that runs the find and replace and takes the two strings, then use transform to run it on all the lines in the vector. This might be a good option if you want to replace more than just "tom".

  6. #6
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thanks Daved!
    I already tried to use nested loops with the previous location as a starting point for the next search and it looks working.

    I guess i can add two or three more nested body for more occurrances but then the code will become redundant.
    So maybe its just better to write a function.
    Last edited by Ducky; 01-26-2008 at 12:20 PM.

  7. #7
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Well after all to write a function is too hard for me yet, i gotta try to learn it still later though.
    So i added a third loop to the program but its not working, i dont understand why.
    It finds two "tom tom" but wont find any if i put three "tom tom tom" in the file.
    Code:
    int main () {
       vector<string> myvector;
       string::iterator it;
       string::iterator it2;
       string::iterator it3;
       size_t found;
       string str;
       string str2 = "tom";
       ifstream file ("1.txt");
        
       for (int i = 0; getline(file, str); i++)
       {      
             myvector.push_back(str);
             it = search (myvector[i].begin(), myvector[i].end(), str2.begin(), str2.end());   // search
    
             if (it != myvector[i].end())                                                  
             {
                 myvector[i][distance(myvector[i].begin(),it)] = 
                              toupper(myvector[i][distance(myvector[i].begin(),it)]);  //  uppercase first found
                 it2 = search (it, myvector[i].end(), str2.begin(), str2.end());      // continue searching
                  
                 if (it2 != myvector[i].end())
                 {
                     myvector[i][distance(it,it2)] = 
                                  toupper(myvector[i][distance(it,it2)]);             // uppercase second found
                     it3 = search (it2, myvector[i].end(), str2.begin(), str2.end());   // continue searching
                     
                     if (it3 != myvector[i].end())
                     {
                         myvector[i][distance(it2,it3)] =
                                      toupper(myvector[i][distance(it2,it3)]);     // uppercase third found      
                     }
                     else
                         cout << myvector[i] << endl;
                  }
                  else 
                      cout << myvector[i] << endl;
             }
             else 
                 cout << myvector[i] << endl;
       }
       file.close();
       system("pause");
       return 0;
    }
    Last edited by Ducky; 01-26-2008 at 12:28 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Implement of a Fast Time Series Evaluation Algorithm
    By BiGreat in forum C Programming
    Replies: 7
    Last Post: 12-04-2007, 02:30 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Replies: 5
    Last Post: 05-25-2004, 04:36 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM