Share via


CString::Replace

This method replaces one 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 method 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.

  int Replace(
TCHAR 
  chOld
  ,
TCHAR 
  chNew ); 

int Replace(
LPCTSTR lpszOld,
LPCTSTR lpszNew ); 

Parameters

  • chOld
    Specifies the character to be replaced by chNew.
  • chNew
    Specifies the character replacing chOld.
  • lpszOld
    Specifies a pointer to a string containing the character to be replaced by lpszNew.
  • lpszNew
    Specifies a pointer to a string containing the character replacing lpszOld.

Return Value

The number of replaced instances of the character. Zero if the string is unchanged.

Example

  //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(_T("hockey"), _T("golf"));
ASSERT(n == 1);
n = strBang.Replace(_T("likes"), _T("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 ".

Requirements

  Windows CE versions: 1.0 and later
  Header file: Declared in Afx.h
  Platform: H/PC Pro, Palm-size PC, Pocket PC

See Also

CString::Remove