Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find all CR+LF's in a string?

Tags:

c#

.net

I'm trying to replace all carrage returns with a <br/> tag in C#. I thought this would take care of everything:

StringBuilder sb = new StringBuilder(s);
sb.Replace(System.Environment.NewLine, @"<br/>");

But apparently not. It doesn't seem to catch CR+LF.

like image 613
broke Avatar asked Dec 03 '22 04:12

broke


2 Answers

That will work if Environment.NewLine is CR+LF, which it's likely to be on Windows. Of course it won't catch the situation where the string actually only contains line feeds, or only contains carriage returns. Perhaps you want:

StringBuilder sb = new StringBuilder(s).Replace("\r\n", "<br/>")
                                       .Replace("\n", "<br/>")
                                       .Replace("\r", "<br/>");

(Note that there's no point in using a verbatim string literal for "<br/>" as there's no backslash in the string, and it's a single line.)

like image 160
Jon Skeet Avatar answered Jan 25 '23 23:01

Jon Skeet


If you know for sure you will replace \r\n why not just use string.replace?

s.replace("\r\n", "<br/>")
like image 20
Lucina Avatar answered Jan 25 '23 23:01

Lucina