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:
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.