0034716b   
   From: pete@versatilecoding.com   
      
   On 2012-04-18 00:05:50 +0000, Jimmy H. said:   
      
   > Hello!   
   > I wrote this replace function:   
   >   
   > #include    
   > using namespace std;   
   >   
   > string replace(const string &input,   
   > const string &to_find,   
   > const string &replacement) {   
   > auto end = input.end();   
   > string result;   
   > for(auto it = input.begin(); it < end; it++) {   
   > if(*it == to_find[0] && equal(to_find.begin(),   
   > to_find.end(),   
   > it)) {   
   > result += replacement;   
   > it += to_find.length() - 1;   
   > } else {   
   > result += *it;   
   > }   
   > }   
   > return result;   
   > }   
   >   
   > It finds all instances of to_find in the string named input and   
   > replaces them (non-destructively) with replacement, returning the   
   > resultant string.   
   >   
   > Three questions:   
   > (a) Are there any glaring (or even not glaring) inefficiencies or   
   > points of bad style in this implementation?   
      
   You could use basic_string::find_first_of to search for the text to be   
   replaced. Let the standard library implementor optimize that search!   
      
   std::string::size_type pos = input.find_first_of(to_find, 0);   
   while (pos != std::string::npos) {   
    // copy up to pos, then copy replacement   
    pos = input.find_first_of(to_find, pos + to_find.length());   
   }   
   // still need to copy the tail of the string, but that's an exercise   
   for the reader.    
      
   That's a sketch; there's probably an off-by-one error, because I always   
   make on when I first write code. Except when I don't.   
      
   In-place replacement is probably slower; every time you replace text,   
   unless the replacement text is the same length as the target text, you   
   copy all of the tail of the string.   
      
   --   
    Pete   
   Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The   
   Standard C++ Library Extensions: a Tutorial and Reference   
   (www.petebecker.com/tr1book)   
      
      
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|