This documentation is archived and is not being maintained.


Updated: October 2009

There are two versions of Replace.The first version replaces one or more copies of a substring by using another substring. Both substrings are null-terminated. The second version replaces one or more copies of a character by using another character. Both versions operate on the character data stored in CStringT.

int Replace(
   PCXSTR pszOld,
   PCXSTR pszNew
int Replace(
   XCHAR chOld,
   XCHAR chNew


A pointer to a null-terminated string to be replaced by pszNew.


A pointer to a null-terminated string replacing pszOld.


The character to be replaced by chNew.


The character replacing chOld.

Returns the number of replaced instances of the character or substring, or zero if the string is not changed.

Replace can change the string length because pszNew and pszOld do not have to be the same length, and several copies of the old substring can be changed to the new one. The function performs a case-sensitive match.

Examples of CStringT instances are CString, CStringA, and CStringW.

For CStringA, Replace works with ANSI or multibyte (MBCS) characters. For CStringW, Replace always works with wide characters.

For CString, the character data type is selected at compile time based on and depends on whether the following constants are defined:

Defined Constant

Character Data Type


Wide characters


Multi-byte characters


Single-byte characters



// typedef CStringT<TCHAR, StrTraitATL<TCHAR, ChTraitsCRT<TCHAR>>> CAtlString;

CAtlString strBang(_T("Everybody likes epee fencing"));
int n = strBang.Replace(_T("epee"), _T("foil"));
ASSERT(n == 1);   

Header: cstringt.h




October 2009

Changed descriptions for pszOld, pszNew.

Customer feedback.