The CString class provides member functions and overloaded operators that duplicate and in some case surpass the string services of the C run-time libraries (for example, strcat). The following sections describe some of the main operations of the CString class.
·To create CString objects from standard C literal strings:
Assign the value of a C literal string to a CString object:
CString myString = "This is a test";
Assign the value of one CString to another CString:
CString oldString = "This is a test";
CString newString = oldString;
As explained more completely in the next section on value semantics, the contents of a CString are copied when one string is assigned to another CString. Thus, the two strings do not share a reference to the actual characters that make up the string.
·To access individual characters in a CString:
You can access individual characters within a CString with the GetAt and SetAt member functions. You can also use the array element operator ( [] ) instead of GetAt to get individual characters (like accessing array elements by index as in standard C-style strings). Index values for CString characters are zero-based.
·To concatenate two CStrings:
Use the concatenation operators (+ or +=) as follows:
CString s1 = "This "; //cascading concatenation
s1 += "is a ";
CString s2 = "test";
CString message = s1 + "big " + s2;
//message contains "This is a big test"
At least one of the arguments to the concatenation operators (+ or +=) must be a CString object, but you can use a constant character string (such as "big") or a char (such as 'x') for the other argument.
·To compare two CStrings:
While the overloaded equality operator (==) and the Compare member functions will determine if two CString objects are equivalent character for character, you can also use the CompareNoCase and Collate member functions to do comparisons that are case insensitive and national- language sensitive. The following table shows the three available CString comparison functions and their equivalent C run-time string functions.
CString function | C run-time function |
Compare | strcmp |
CompareNoCase | stricmp |
Collate | strcoll |
The CString class overrides the relational operators (<, <=, >=, >, ==, and !=) to use the Compare function, so you can compare two CStrings using these operators, as shown here:
CString s1( "Tom" );
CString s2( "Jerry" );
if( s1 < s2 )
...