MFC - Strings

Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++.
This string is actually a one-dimensional array of characters which is terminated by a null character '\0'.
This string is actually a one-dimensional array of characters which is terminated by a null character '\0'.
A null-terminated string contains the characters that comprise the string followed by a null.
A null-terminated string contains the characters that comprise the string followed by a null.
Here is the simple example of character array.
char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0' };
Following is another way to represent it.
char word[] = "Hello, World";
Microsoft Foundation Class (MFC) library provides a class to manipulate string called CString. Following are some important features of CString.
CString does not have a base class.
CString does not have a base class.
A CString object consists of a variable-length sequence of characters.
A CString object consists of a variable-length sequence of characters.
CString provides functions and operators using a syntax similar to that of Basic.
CString provides functions and operators using a syntax similar to that of Basic.
Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays.
Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays.
Here is the constructor of CString.
CString
Constructs CString objects in various ways
Here is a list of Array Methods −
GetLength
Returns the number of characters in a CString object.
IsEmpty
Tests whether a CString object contains no characters.
Empty
Forces a string to have 0 length.
GetAt
Returns the character at a specified position.
SetAt
Sets a character at a specified position.
Here is a list of Comparison Methods −
Compare
Compares two strings (case sensitive).
CompareNoCase
Compares two strings (case insensitive).
Here is a list of Extraction Methods −
Mid
Extracts the middle part of a string (like the Basic MID$ function).
Left
Extracts the left part of a string (like the Basic LEFT$ function).
Right
Extracts the right part of a string (like the Basic RIGHT$ function).
SpanIncluding
Extracts the characters from the string, which are in the given character set.
SpanExcluding
Extracts the characters from the string which are not in the given character set.
Here is a list of Conversion Methods.
MakeUpper
Converts all the characters in this string to uppercase characters.
MakeLower
Converts all the characters in this string to lowercase characters.
MakeReverse
Reverses the characters in this string.
Format
Format the string as sprintf does.
TrimLeft
Trim leading white-space characters from the string.
TrimRight
Trim trailing white-space characters from the string.
Here is a list of Searching Methods.
Find
Finds a character or substring inside a larger string.
ReverseFind
Finds a character inside a larger string; starts from the end.
FindOneOf
Finds the first matching character from a set.
Here is a list of Buffer Access Methods.
GetBuffer
Returns a pointer to the characters in the CString.
GetBufferSetLength
Returns a pointer to the characters in the CString, truncating to the specified length.
ReleaseBuffer
Releases control of the buffer returned by GetBuffer 
FreeExtra
Removes any overhead of this string object by freeing any extra memory previously allocated to the string.
LockBuffer
Disables reference counting and protects the string in the buffer. 
UnlockBuffer
Enables reference counting and releases the string in the buffer. 
Here is a list of Windows-Specific Methods.
AllocSysString
Allocates a BSTR from CString data.
SetSysString
Sets an existing BSTR object with data from a CString object.
LoadString
Loads an existing CString object from a Windows CE resource.
Following are the different operations on CString objects −
You can create a string by either using a string literal or creating an instance of CString class.
BOOL CMFCStringDemoDlg::OnInitDialog() {

   CDialogEx::OnInitDialog();

   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);         // Set big icon
   SetIcon(m_hIcon, FALSE);       // Set small icon

   CString string1 = _T("This is a string1");
   CString string2("This is a string2");

   m_strText.Append(string1 + L"\n");
   m_strText.Append(string2);

   UpdateData(FALSE);

   return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed, you will see the following output.
You can create an empty string by either using an empty string literal or by using CString::Empty() method. You can also check whether a string is empty or not using Boolean property isEmpty.
BOOL CMFCStringDemoDlg::OnInitDialog() {
   CDialogEx::OnInitDialog();

   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);            // Set big icon
   SetIcon(m_hIcon, FALSE);           // Set small icon

   CString string1 = _T("");
   CString string2;
   string2.Empty();

   if(string1.IsEmpty())
      m_strText.Append(L"String1 is empty\n");
   else
      m_strText.Append(string1 + L"\n");
   
   if(string2.IsEmpty())
      m_strText.Append(L"String2 is empty");
   else
      m_strText.Append(string2);
   UpdateData(FALSE);
   return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
To concatenate two or more strings, you can use + operator to concatenate two strings or a CString::Append() method.
BOOL CMFCStringDemoDlg::OnInitDialog() {
   CDialogEx::OnInitDialog();

   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);              // Set big icon
   SetIcon(m_hIcon, FALSE);              // Set small icon

   //To concatenate two CString objects
   CString s1 = _T("This ");           // Cascading concatenation
   s1 += _T("is a ");
   CString s2 = _T("test");
   CString message = s1;
   message.Append(_T("big ") + s2);
   // Message contains "This is a big test".

   m_strText = L"message: " + message;

   UpdateData(FALSE);

   return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in a CString object.
BOOL CMFCStringDemoDlg::OnInitDialog() {
   CDialogEx::OnInitDialog();
   
   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);              // Set big icon
   SetIcon(m_hIcon, FALSE);              // Set small icon

   CString string1 = _T("This is string 1");
   int length = string1.GetLength();
   CString strLen;

   strLen.Format(L"\nString1 contains %d characters", length);
   m_strText = string1 + strLen;

   UpdateData(FALSE);

   return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
To compare two strings variables you can use == operator
BOOL CMFCStringDemoDlg::OnInitDialog() {
   CDialogEx::OnInitDialog();
   
   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);            // Set big icon
   SetIcon(m_hIcon, FALSE);          // Set small icon

   CString string1 = _T("Hello");
   CString string2 = _T("World");

   CString string3 = _T("MFC Tutorial");
   CString string4 = _T("MFC Tutorial");

   if (string1 == string2)
      m_strText = "string1 and string1 are same\n";
   else
      m_strText = "string1 and string1 are not same\n";

   if (string3 == string4)
      m_strText += "string3 and string4 are same";
   else
      m_strText += "string3 and string4 are not same";

   UpdateData(FALSE);

   return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
 Print
 Add Notes
 Bookmark this page