Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 9 Strings Visual C++ and MFC Fundamentals


char* strchr(const char* S, char c);

This function takes two arguments. The second argument, c, specifies what character to
look for in the first argument, S, which is a string. If character c appears in string S, the
function would return a new string whose value starts at the first occurrence of c in S. If
the character c does not appear in the string S, then the function would return NULL.

The strrchr() function examines a string starting at the end (right side) of the string and
looks for the first occurrence of a certain character. Its syntax is:

char* strrchr(const char* S, char c);

The first argument is the string that needs to be examined. The function will scan string S
from right to left. Once it finds the first appearance of the character c in the string, it
would return a new string whose value starts at that first occurrence. If the character c
does not appear in the string S, then the function would return NULL.

9.3.2 Sub-Strings............................................................................................


The strstr() function looks for the first occurrence of a sub-string in another string and
returns a new string as the remaining string. Its syntax is:

char* strstr(const char* Main, const char *Sub);

The first argument of the function is the main string that would be examined. The
function would look for the second argument, the Sub string appearance in the Main
string. If the Sub string is part of the Main string, then the function would return a string
whose value starts at the first appearance of Sub and make it a new string. If Sub is not
part of the Main string, the function would return a NULL value.

9.4 The CString Class.........................................................................................


9.4.1 Introduction...........................................................................................


The MFC library provides its own data types and a class for string manipulation. The
class is called CString. To declare a string with the CString class, you can use one of its
constructors. To initialize a string when declaring it, you can pass a string to one of the
following constructors:

CString(const unsigned char* psz);
CString(LPCWSTR lpsz);
CString(LPCSTR lpsz);

These constructors take a null-terminated string as argument. Once the variable has been
declared, an amount of memory space is assigned for its use. If for any reason the
memory or enough memory could not be allocated, an exception would occur. If the
space allocated for the variable is higher than necessary, at any time, you can reduce it by
calling the CString::FreeExtra() method. Its syntax is:

void FreeExtra();
Free download pdf