We recommend using Visual Studio 2017
This documentation is archived and is not being maintained.


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 that replaces 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 works with wide characters.

For CString, the character data type is selected at compile time, based on whether the constants in the following table 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