Export (0) Print
Expand All


Visual Studio 6.0


int Replace( TCHAR chOld, TCHAR chNew );

int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );

Return Value

The number of replaced instances of the character. Zero if the string isn't changed.



The character to be replaced by chNew.


The character replacing chOld.


A pointer to a string containing the character to be replaced by lpszNew.


A pointer to a string containing the character replacing lpszOld.


Call this member function to replace a character with another. The first prototype of the function replaces instances of chOld with chNew in-place in the string. The second prototype of the function replaces instances of the substring lpszOld with instances of the string lpszNew

The string may grow or shrink as a result of the replacement; that is, lpszNew and lpszOld do not have to be equal in length. Both versions perform case-sensitive matches.


//First example, with old and new equal in length.

CString strZap("C--");
int n = strZap.Replace('-', '+');
ASSERT(n == 2);
ASSERT(strZap == "C++");

//Second example, old and new are of different lengths.

CString strBang("Everybody likes ice hockey");
n = strBang.Replace("hockey", "golf");
ASSERT(n == 1);
n = strBang.Replace("likes", "plays");
ASSERT(n == 1);
n = strBang.Replace("ice", NULL);
ASSERT(n == 1);
ASSERT(strBang == "Everybody plays  golf");

// note that you now have an extra space in your
// sentence. To remove the extra space, include it
// in the string to be replaced, i.e.,"ice ".

CString OverviewClass MembersHierarchy Chart

See Also   CString::Remove

© 2014 Microsoft