Rogue Wave Banner

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

An Introductory Example

The following example calls on several essential features of the string classes. Basically, 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/regexp.h>
#include <rw/rstream.h>

main(){
  RWCString a;                     //1 create string object a

  RWCRegexp re("V[0-9]\\.[0-9]+"); //2 define regular expression  
  while( a.readLine(cin) ){        //3 read standard input into a 
    a(re) = "V4.0";                //4 replace matched expression
    cout << a << 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 a, reads lines from standard input into a, and searches a 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 power of this operation lies in the expression:

a(re) = "V4.0";

where() is an example of an overloaded operator. As you know, an overloaded operator is one which can perform more than one function, depending on context or argument.

In the example, the function call operator RWCString::operator()is overloaded to take an argument of type RWCRegexp, the regular expression. The operator returns either a substring that delimits the regular expression, or a null substring if a matching expression cannot be found. The program then calls the substring assignment operator, which replaces the delimited string with the contents of the right hand side, or does nothing if this is the null substring. Because Tools.h++ provides the overloaded operator, you can do a search and replace on the defined regular expression all in a single line.

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 another 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 Class Reference for details on the string classes.


Previous file Table of Contents Next file