Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 9 Strings Visual C++ and MFC Fundamentals


9.6.3 Character and String Removal...........................................................


Besides the CString(LPCTSTR lpch, int nLength) constructor, the Left(), the Mid(),
and the Right() method, another technique you can use to create a sub string consists of
deleting characters from an existing string. This can be done by calling the
CString::Delete() method. Its syntax is:

int Delete(int nIndex, int nCount = 1);

The nIndex argument specifies the first character of the range. If you pass only this
argument, only the character at position nIndex will be deleted. If you want to delete
more than one character, pass the desired number as the nCount argument. If the value of
nCount is higher than the remaining number of characters from nIndex position, all
characters to the right will be deleted.

If you want to remove all occurrences of a particular character in a string, you can call the
Remove() method. Its syntax is:

int CString::Remove(TCHAR ch);

This method scans the string looking for the ch character. Whenever it finds it, it deletes
it. This operation is performed using case sensitivity. This means that only the exact
match with case of ch would be deleted.

9.6.4 Replacing String Occurrences...........................................................


Besides the CString::SetAt() method, you can also use the Replace() method to replace
a character of the string with another character. The syntaxes of the Replace() method
are:

int Replace(TCHAR chOld, TCHAR chNew);
int Replace(LPCTSTR lpszOld, LPCTSTR lpszNew);

The Replace() method replaces each occurrence of the chOld argument. Whenever it
finds it, it replaces it with the chNew character. Here is an example:

void CExerciseDlg::OnMsgBox()
{
// TODO: Add your control notification handler code here
CString Msg("The name you entered is not in our records.\n"
"If you think there is a mistake, please contact HR.\n"
"You can also send an email to [email protected]");
Msg.Replace("HR", "Human Resources");
Msg.Replace(".com", ".net");

MessageBox(Msg, "Failed Logon Attempt");
}
Free download pdf