views:

770

answers:

3

I've spent the last hour and a half trying to figure out how to run a simple search and replace on a string object in C++.

I have three string objects.

string original, search_val, replace_val;

I want to run a search command on original for the search_val and replace all occurrences with replace_val.

NB: Answers in pure C++ only. The environment is XCode on the Mac OSX Leopard.

+4  A: 
size_t start = 0;
while(1) {
  size_t where = original.find(search_val, start);
  if(where==npos) {
    break;
  }
  original.replace(where, search_val.size(), replace_val);
  start = where + replace_val.size();
}
Alex Martelli
thank you for your answer
yuval
+18  A: 

A loop should work with find and replace

void searchAndReplace(std::string& value, std::string const& search,std::string const& replace)
{
    std::string::size_type  next;

    for(next = value.find(search);        // Try and find the first match
        next != std::string::npos;        // next is npos if nothing was found
        next = value.find(search,next)    // search for the next match starting after
                                          // the last match that was found.
       )
    {
        // Inside the loop. So we found a match.
        value.replace(next,search.length(),replace);   // Do the replacement.
        next += replace.length();                      // Move to just after the replace
                                                       // This is the point were we start
                                                       // the next search from. 
    }
}
Martin York
could you please explain how your code works?thank you :)
yuval
Added comments.
Martin York
It's a small nit to pick, but your function name has a typo ("Repalce") which seems a little out of place in your, very elegant and well formatted, code.
A. Levy
@Levy: One can only strive for perfection but attaining it is the domain of deities (thus if my only mistake is spelling I am happy).
Martin York
thank you SO much!
yuval
I agree this is an elegent piece of code. My only recommendation is to not use verbs for your parameters/variables because they look like function name (replace even is a function name). So your replace() call could read something like target.replace(next,search_string.length(),replacement)
Roger Nelson
+1  A: 

For comparison here is the function in pure C: http://www.pixelbeat.org/libs/string%5Freplace.c

pixelbeat
what does the phrase "string interpolation" mean? I found it in the header of the link you provided.
Beh Tou Cheh
If you look up "interpolate" you should get a description. for example shell variable interpolation is the process of replacing $name with "value".
pixelbeat