Replace "\r\n" by "_"

M

Marty

Hi,

I would like to replace "\r\n" by "_" within a specific string.

I tried :
strMyString.Replace('\r', '_');
strMyString.Replace('\n', '_');
or
strMyString.Replace(System.Environment.NewLine, '_');

and it doesn't work, what is missing?

Thank you!
Marty
 
V

VJ

Marty

This works for me....

string strText = "Text me " + Environment.NewLine + "Text me " +
Environment.NewLine;
strText = strText.Replace(Environment.NewLine, "_");

or this works..

string strText = "Text me " + Environment.NewLine + "Text me " +
Environment.NewLine;

strText = strText.Replace("\r\n", "_");

Vijay
 
J

John Bowman

Marty,

You almost had it. The Replace() method returns the modified string. Try
this...

string strMyString = "This is\r\n some line\r wrapping\n text";
strMyString = strMyString.Replace("\r\n", "_").Replace("\r",
"_").Replace("\n", "_");

John
 
J

Jianwei Sun

I think you have to assign it to a different string, this is a little
bit differnet with the C++ string.
 
J

Jon Skeet [C# MVP]

Marty said:
I would like to replace "\r\n" by "_" within a specific string.

I tried :
strMyString.Replace('\r', '_');
strMyString.Replace('\n', '_');
or
strMyString.Replace(System.Environment.NewLine, '_');

and it doesn't work, what is missing?

Strings are immutable - String.Replace doesn't change the contents of
the string you call it on; instead, it returns a new string.

To achieve your stated aim, you should use:

strMyString = strMyString.Replace("\r\n", "_");

Note that your first attempt would replace bare carriage returns and
bare line feeds with underscores, and would replace "\r\n" with "__"
instead of "_".
Your second attempt is closer, but will only replace "\r\n" on Windows
- on other platforms, it will replace whatever the platform default
newline string is with "_".

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top