We help IT Professionals succeed at work.

CString replace chars with newline

edc asked
Hello all,
   I have what seems to me to be a very simple task, but one that is giving me fits.  I have a CString variable, with which I want to use the Replace method to replace a set of one or more characters with a newline character.  What I first tried was this:

CString str;
CString OldChars("Something");

str.Replace(OldChars, '\r\n');

Needless to say this did not work.  Can someone tell me how to do this?

Watch Question

Top Expert 2012
Use the following function to do that:

ULONG   ReplaceString   (   CString&    rstr,
                            CString&    rstrFind,
                            CString&    rstrReplace
    int     nPos;
    ULONG   ulCount         =   0;
    ULONG   ulFindLength    =   rstrFind.GetLength  ();

    if  (   -1  !=  (   nPos    =   rstr.Find   (   rstrFind)))
            while   (   -1  !=  (   nPos    =   rstr.Find   (   rstrFind)))
                        rstr    =       rstr.Left   (   nPos)
                                    +   rstrReplace
                                    +   rstr.Right  (       rstr.GetLength  ()
                                                        -   nPos
                                                        -   ulFindLength


    return  (   ulCount);

So, you could just

CString OldChars("Something");

ReplaceString ( OldChars, CString( "thing"), CString ( "\r\n"));

and will get "Some\r\n"


Fantastic!  Thanks for your help.
AxterSenior Software Engineer

All you had to do to fix your code was to change your single quote to double quotes.
CString str = "Hello\nWorld\nMy name is\nAxter\n";
CString OldChars("\n");
str.Replace(OldChars, "\r\n");
AxterSenior Software Engineer

CString has to Replace() functions.
One works with single char and the other works with strings.
int Replace( TCHAR chOld, TCHAR chNew );

int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );

The reason your code did not work is because you were mixing a single char with a string.

Even though you have more then one charactor inside the single quotes, the compiler will still compile this to a single character, and ignore the remaining charactors after the first one.

You could have also compiled your code using the following syntax:
str.Replace(CString('\n'), "\r\n");

You would use the above code if you had a single charactor varaiable type that needed to be replace by a string (multiple chars).