Chapter 9 Strings Visual C++ and MFC Fundamentals
9.6 Sub Strings.....................................................................................................
9.6.1 Introduction...........................................................................................
A sub string is a character or a group of characters that is part of another string.
Therefore, to create a string, you must first have a string as basis.
When declaring and initializing a CString variable, although you can provide as many
characters as posible, you may want the variable to actually hold only part of the string
value. Based on this, to create a sub string when declaring a CString variable, you can use
the following constructor:
CString(LPCTSTR lpch, int nLength);
When using this constructor, provide the whole string as a the null-terminated lpch string.
To specify the number of characters for the sub string variable, provide an integer value
for the nLength argument. Here is an example:
void CExerciseView::OnDraw(CDC* pDC)
{
CExerciseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
CString CofV = "Commonwealth of Virginia";
CString Sub(CofV, 12);
pDC->TextOut(10, 20, Sub);
}
As you may realize from this constructor, its sub string is built from the left side of the
string and starts counting characters towards the right. Once it reaches the nLength
number of characters, it creates the new string and ignores the characters beyond
nLength.
If the string has already been initialized and you want to create a sub string made of some
characters from its left side, you can call the CString::Left() method. Its syntax is:
CString Left(int nCount) const;
This method starts counting characters from the left to nCount characters and returns a
new string made of those nCount characters. Here is an example:
void CExerciseView::OnDraw(CDC* pDC)
{
CExerciseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);