How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Hcabnettek picture Hcabnettek · Dec 30, 2009 · Viewed 196.3k times · Source

I am trying to persist string from an ASP.NET textarea. I need to strip out the carriage return line feeds and then break up whatever is left into a string array of 50 character pieces.

I have this so far

var commentTxt = new string[] { };
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb != null)
  commentTxt = cmtTb.Text.Length > 50
      ? new[] {cmtTb.Text.Substring(0, 50), cmtTb.Text.Substring(51)}
      : new[] {cmtTb.Text};

It works OK, but I am not stripping out the CrLf characters. How do I do this correctly?

Answer

Matt Greer picture Matt Greer · Dec 30, 2009

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);