Visual C++ and MFC Fundamentals Chapter 10: Characteristics of a Window's Frame
}
9.5 Working with Individual Characters.........................................................
9.5.1 Character Indexing..............................................................................
The characters or symbols that compose a CString variable are stored in an array of
characters. To get to the character or symbol at a specific position, you can use the square
brackets, the same way you would proceed for an array. This is possible because the
square bracket operator is loaded for the CString class:
TCHAR operator []( int nIndex ) const;
Like an array, the characters of a CString value are stored in a 0-based index, meaning
the first character is at index 0, the second at 2, etc. Imagine you have a string declared
and initialized as:
CString Capital(“Antananarivo”);
To get the 5th character of this string, you could write:
CString Fifth = Capital[4];
Here si an example:
void CExerciseView::OnDraw(CDC* pDC)
{
CExerciseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
CString Capital("Antananarivo");
CString Fifth = Capital[4];
pDC->TextOut(10, 20, Capital);
pDC->TextOut(10, 40, Fifth);
}
Besides the square brackets, to access the character stored at a certain position in a string,
you can call the GetAt(). Its syntax is:
TCHAR GetAt( int nIndex ) const;
Here is an example of using it: