Thursday, February 19, 2015

Manipulate Strings In Mfc

The STL Library of pure C++ has the "string" class. The Microsoft Foundation Class (MFC) Library has its own salvation: the CString class. MFC's CString provides all the features a programmer needs to handle and manipulate a string. Although not an exhaustive treatise on the class, this article illustrates its most frequently used features so that by the end you can be up and running.


Instructions


1. Initialize a CString object. CString has many constructors. You can instantiate a CString object with char, char*, TCHAR or no parameters. It supports the "=" operator, so you can assign empty objects a value.


Example:


CString s1, s2("Hello");


s1 = s2; // s1 has the value of "Hello"


2. Obtain the length of a CString object. The "GetLength()" function returns an unsigned integer that is the length of the string.


3. Concatenate one CString object with another. The easy way to add two strings is through the "+" operator.


Example:


CString s1("first name"), s2(" last name");


s1 = s1 + s2;


4. Do comparisons with CString. You can use the "CompareNoCase()" function to do case-insensitive comparisons; the "==" operator supports case-sensitive comparisons.


Example:


CString s("Let's see if they are equal");


If("Let's see if they are equal" == s) {


MessageBox("Case sensitive");


}


// OR


if("let's see if they are equal" == s) {


MessageBox("Case insensitive");


}


5. Look for a substring inside an MFC CString object. You can do this by overloading the "Find()" function to accept strings and single characters. The search takes place from left to right and returns the position of the substring.


CString s("The search capabilities of CString");


int pos = s.Find('s');


int pos2 = s.Find("of");


6. Format the data. "Format()" works similar to the C printf function.


CString s;


int num = 80;


char arr[] = "Number: ";


s.Format(("%s %d", arr, num);