An Introductory Example
The following example uses several essential features of the string classes. It shows the steps RWCString would take to substitute a new version number for the old ones in a piece of documentation.
#include <rw/cstring.h>
#include <rw/tools/regex.h>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
RWCString str; //1 create string object ‘str’
RWTRegex<char> re("V[0-9]\\.[0-9]+"); //2 define regular expression
while (str.readLine(cin)) //3 read standard input into object str
{
re.replace(str, "V4.0", 0); //4 replace matched expression
std::cout << str << std::endl;
}
return 0;
}
Program Input:
This text describes V1.2. For more
information see the file install.doc.
The current version V1.2 implements...
Program Output:
This text describes V4.0. For more
information see the file install.doc.
The current version V4.0 implements...
The code here describes the activity of the class. RWCString creates a string object str, reads lines from standard input into str, and searches str for a pattern matching the defined regular expression "V[0-9]\\.[0-9]+". A match would be a version number between V0 and V9; for example, V1.2 and V1.22, but not V12.3. When a match is found, it is replaced with the string “V4.0”.
The replacement is performed by RWTRegex<T>::replace(). The string str is passed to the function as a reference argument. After the call to replace, str is updated, replacing all occurrences of the pattern in the regular expression re with the text V4.0. The third argument of replace() is the number of occurrences of the pattern to be replaced. The 0 value indicates that all occurrences should be replaced.
You will notice that you need two backlashes in “V[0-9]\\.[0-9]+” to indicate that the special character “.” is to be read literally as a decimal point. That's because the compiler removes one backslash when it evaluates a literal string. The remaining backslash alerts the regular expression evaluator to read whatever character follows literally.
In the next example, RWCString uses an overloaded operator to concatenate the strings s1 and s2. The toUpper member function converts the strings from lower to upper case, and the results are sent to cout:
 
RWCString s1, s2;
cin >> s1 >> s2;
cout << toUpper(s1+s2);
See the SourcePro API Reference Guide for details on the string classes.