Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 9 Strings Visual C++ and MFC Fundamentals


void CExerciseView::OnDraw(CDC* pDC)
{
CExerciseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);

CString Capital("Antananarivo");
CString Fifth = Capital.GetAt(4);

pDC->TextOut(10, 20, Capital);
pDC->TextOut(10, 40, Fifth);
}

9.5.2 Character Insertion..............................................................................


As stated already, a CString value is in fact an array of characters. This allows you to
locate a position in the string and change its character. To do this, you can use the
SetAt() method. Its syntax is:

void SetAt(int nIndex, TCHAR ch);

Here is an example:

#include <afxwin.h>
#include <iostream>
using namespace std;

int main()
{
CString Object("Wall");

cout << "Object: " << (LPCTSTR)Object << endl;
Object.SetAt(1, 'e');
cout << "Name: " << (LPCTSTR)Object << endl;

return 0;
}

9.5.3 Finding a Character.............................................................................


Scanning a string consists of visiting or examining each one of its characters. One of the
reasons you would do this is to look for a particular character that may be part of the
string.

To scan a string for a character, you can call the CString::Find() method. It is
overloaded as follows:

int Find(TCHAR ch) const;
int Find(TCHAR ch, int nStart) const;

To look for a single character in the string, pass a character value or variable as argument.
In this case, the string would be examined from the most left character to the right. If you
want the scanning to start at a certain position instead of from the most left character,
besides the character to look for, pass a second argument as nStart. If the character is
Free download pdf