CString

Win32++

CString

Introduction

CStrings are used for text strings. They can prove easier and safer to use than TCHAR arrays. CStrings are easily copied and modified, and handle null termination automatically.

The CString class provided with Win32++ is designed to behave in much the same way as CStrings provided with other frameworks like MFC and ATL.

Assigning CStrings

There are several ways to assign a CString. These include:

CString str1 = _T("Text string");
CString str2(_T("Text string"));

TCHAR szText[80] = _T("Text String");
CString str3 = szText;
CString str4 = _T('T'); // a single character
CString str5 = str1; // copy a CString
CString str6 = str1 + str2; // Concatenate two strings
// Assign a string like a c-style printf CString str7; str7.Format(_T("There are %d apples"), 5);

Modifying CStrings

The CString class has several member functions for modifying the contents of a CString. These include:

  •  Insert can be used to insert characters into the string.
  •  Delete can be used to remove characters from the string.
  •  MakeUpper and MakeLower converts the string to upper or lower case.
  •  Trim, TrimLeft and TrimRight can trim characters from the CString.
  •  Remove the specified character from the string.
  •  Replace an old sub-string with a new one.
  •  SetAt changes the character at the specified index.
  •  Truncate reduces the length of the string to the specified amount.

Coding Example:

// insert the word "sat" into the string
CString str("The cat on the mat");
str.Insert(8, _T("sat "));

// Convert the string to upper case
str.MakeUpper();

Accessing elements of a CString

Parts of a CString can be accessed in several different ways:

  •  Left, Mid and Right can be used to extract characters from the string.
  •  GetAt retrieves the character at the specified location.

Coding Example:

CString str1("The cat sat on the mat");

// Copy 3 characters, beginning at index 4 to str2
CString str2 = str1.Mid(4, 3);
assert(str2 == _T("cat");

Finding elements in the CString

The following functions can be used to find the index of elements in the CString:

  •  Find and ReverseFind
  •  FindOneOf

Coding Example:

CString str( "The cat sat on the mat" );
int i = str.Find(_T("cat"));
assert(i == 4);

Using GetBuffer and ReleaseBuffer

CString can provide a pointer to an internal buffer. This allows a CString to be used in places where we would write to a character array.

Coding Example:

Here we use GetBuffer to allocate a buffer for use by the GetWindowText function.

int nLength = ::GetWindowTextLength(m_hWnd);
CString str;
::GetWindowText(m_hWnd, str.GetBuffer(nLength), nLength+1);
str.ReleaseBuffer();
Note: We must call ReleaseBuffer when we have finished writing to the buffer. This copies the contents of the buffer into the CString and frees the allocated buffer.