How to Replace Arbitrary Text in String in C++

The C++ string library has several useful functions for manipulating strings, but no general search and replace. Although there is a lot of information on optimized algorithms for implementing arbitrary text replacement, many algorithms involve complex data structures and hard-to-follow techniques such as pointer arithmetic. For most programs, search and replace isn't a performance bottleneck, so it makes more sense to use a simple, easily understandable algorithm. This is possible by taking advantage of some of the existing string functions to handle the low-level manipulation.

Instructions

    • 1

      Write the outline of your string replacement function:

      string replaceSubstring(string source, string match, string replace)
      {
      string out = "";
      return out;
      }

    • 2

      Add a loop that finds all substring matches in the string. The variable lastpos will be helpful when you start adding the code to build the new string:

      size_t pos = 0; //Start searching at the first character
      size_t lastpos = 0;
      while((pos = source.find(match, pos)) != string::npos) //loop until no matches are found
      {
      pos = pos + match.lengh(); //Start the search for the next match at the end of this match
      lastpos = pos;
      }

    • 3

      Build the output string as matches are found:

      size_t pos = 0; //Start searching at the first character
      size_t lastpos = 0;
      while((pos = source.find(match, pos)) != string::npos) //loop until no matches are found
      {
      output += source.substr(lastpos, pos - lastpos); //Add all characters that were skipped over
      output += replace;
      pos = pos + match.lengh(); //Start the search for the next match at the end of this match
      lastpos = pos;
      }
      output += source.substr(lastpos); //Add the remainder of the source string

Related Searches:

References

Comments

Related Ads

Featured