Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 9 Strings Visual C++ and MFC Fundamentals


this class, on top of the file where you will need access to it, include the string library
and call the std namespace. To do this, you would type:

#include <string>
using namespace std;

Therefore, to declare a variable using the STL's string class, use one of its constructors.
For example, you can use the default constructor as follows:

string FirstName;

To initialize a string variable, you can provide its value between parentheses. Here is an
example:

string FullName(“Jules Andong”);

The STL's string class is not natively supported in MFC applications. Therefore, in order
to use it, you must convert its value to a null-terminated string. To allow this, the string
class provides the c_str() member function. Its syntax is:

const E *c_str() const;

Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
string StrName("Central African Republic");

pDC->TextOut(20, 22, StrName.c_str(), 24);
}

9.1.3 The Length of a String........................................................................


The length of a string is the number of characters that the string contains. To get the
length of a string declared using the char, the CHAR, the TCHAR, the _TCHAR or one
of the Win32 API's data types, you can use the strlen() function. Its syntax is:

size_t strlen(const char *String);

This function returns the number of characters of the String argument. Here is an
example:

void CExoView::OnDraw(CDC* pDC)
{
char StrName[] = "Euzhan Palcy";
int Len = strlen(StrName);

pDC->TextOut(20, 22, StrName, Len);
}

To get the length of a string declared using the string class, call the length() member
function. Its syntax is:

size_type length() const;
Free download pdf