Link to home
Start Free TrialLog in
Avatar of edc
edc

asked on

CString replace chars with newline

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?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of edc
edc

ASKER

Fantastic!  Thanks for your help.
All you had to do to fix your code was to change your single quote to double quotes.
Example:
CString str = "Hello\nWorld\nMy name is\nAxter\n";
CString OldChars("\n");
     
str.Replace(OldChars, "\r\n");
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.

'\r\n'
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).