Kip Irvine home page | C++ Book Page

Using the CString Class in Microsoft Visual C++ 5.0

The CString class simplifies string handling in C++ by providing the same functionality that you may be used to when programming other laguages such as Pascal or Visual Basic. Memory is automatically allocated for characters in CString objects. Your program must #include the file afx.h in order to use the CString class. (Other classes defined in this file include CTimeSpan, CTime, CFile, and CStdioFile.) The following program demonstrates some of the more common operations:

#include <iostream.h>
#include <afx.h> 

void main()
{
  CString myString = "This is a test";
  cout << myString.GetLength() << endl;

  CString n1("George"); // conversion constructor
  CString n2( n1 );     // copy constructor

  if( n1 == n2 )        // overloaded == operator
    cout << "n1 and n2 are the same.\n";

  n1 += " Washington";   // concatenate operator
  cout << n1 << endl;

  int z = n1.Find("ton"); // find a substring
  if( z == -1 )
    cout << "substring was not found.\n";
  else
    cout << "\"ton\" was found in position " << z << endl;

  // Concatenate a CString to a string literal:
  cout << (myString + " of the CString class.\n\n");

  // Read individual characters:
  cout << myString[3] << "," << myString[0] << endl;

  // The [ ] operator cannot be used to modify characters
  // in a string. Instead, you must use the SetAt() function:

  //myString[3] = 'z';      // illegal use of operator
  myString.SetAt(3, 'z');   // modifies a character

  myString.MakeReverse();   // reverse the characters
  cout << myString << endl;

  char buf[30];
  strcpy(buf, n1);          // implicit conversion to char * 
  cout << buf << endl;

  n2.MakeUpper();           // convert to uppercase
  cout << n2 << endl;
}