Replacing, Inserting, and Deleting Substrings

The ability to manipulate the contents of an IString is one of the greatest advantages of the IString class over the traditional method of using string.h functions to manipulate arrays of characters. Consider, for example, a function that perform the following changes on a string. Issues that you need to address when using arrays of characters, but that are handled for you by the IString class, are shown in parentheses:

  1. Replace all occurrences of Blue with Yellow (string must be expanded by two characters for each replacement, and text after the replacement must be shifted out).
  2. Replace all occurrences of Orange with Pink (string must be shortened by two characters for each replacement).
  3. Delete the sixth word of the string. (How are words delimited? By spaces? Carriage returns? Tab characters? What about multiple adjacent whitespace characters?)
  4. Insert the word Dark as the fourth word or at the end of the string if the string has fewer than three words. (String must be extended. How are words delimited? Do you add a space before or after the word?).

You can easily handle the above requirements using IString member functions. The sample function fixString() below implements the requirements. Numbered comments correspond to the numbers of the requirements:

// Inserting, deleting and replacing substrings
#include <iostream.h>
#include <istring.hpp>
void fixString(IString&);
void main() {
   IString Str1="Light Blue and Green are nice colors. ";
   Str1+="But so are Red and Orange.";
   cout << Str1 << endl; 
   fixString(Str1);
   cout << Str1 << endl;
   }
void fixString(IString &myString) {
   myString.change("Blue", "Yellow");       // 1. Change Blue to Yellow
   myString.change("Orange", "Pink");       // 2. Change Orange to Pink
   myString.removeWords(6,1);               // 3. Remove words, starting at word 6,
                                            // for a total of 1 word. 
   int Word4=myString.indexOfWord(4);
   if (Word4>0)                             // 4. Insert "Dark" as fourth word
      myString.insert("Dark ",Word4-1);     // or at end of string if string
   else                                     // has fewer than 4 words. The
      myString+=" Dark";                    // insertion occurs 1 byte before
   }                                        // word 4 (otherwise it inserts
                                            // in the middle of word 4). 

This program produces the following output:

Light Blue and Green are nice colors. But so are Red and Orange.
Light Yellow and Dark Green are colors. But so are Red and Pink.