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

C#asp.netStringCarriage Return

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

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

Solution 2 - C#

The .Trim() function will do all the work for you!

I was trying the code above, but after the "trim" function, and I noticed it's all "clean" even before it reaches the replace code!

String input:       "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."

Source: http://www.dotnetperls.com/trim

Solution 3 - C#

This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.

var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, @"(?:\r\n|\n|\r)"));
Console.Write(newString);

// prints:
// the quick brown fox jumped over the box and landed on some rocks.

Solution 4 - C#

Nicer code for this:

yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);

Solution 5 - C#

Here is the perfect method:

Please note that Environment.NewLine works on on Microsoft platforms.

In addition to the above, you need to add \r and \n in a separate function!

Here is the code which will support whether you type on Linux, Windows, or Mac:

var stringTest = "\r Test\nThe Quick\r\n brown fox";

Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");

stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);

Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();

Solution 6 - C#

Try this:

private void txtEntry_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string trimText;

            trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
            this.txtEntry.Text = trimText;
            btnEnter.PerformClick();
        }
    }

Solution 7 - C#

Assuming you want to replace the newlines with something so that something like this:

the quick brown fox\r\n
jumped over the lazy dog\r\n

doesn't end up like this:

the quick brown foxjumped over the lazy dog

I'd do something like this:

string[] SplitIntoChunks(string text, int size)
{
    string[] chunk = new string[(text.Length / size) + 1];
    int chunkIdx = 0;
    for (int offset = 0; offset < text.Length; offset += size)
    {
        chunk[chunkIdx++] = text.Substring(offset, size);
    }
    return chunk;
}    

string[] GetComments()
{
    var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox; 
    if (cmtTb == null)
    {
        return new string[] {};
    }
    
    // I assume you don't want to run the text of the two lines together?
    var text = cmtTb.Text.Replace(Environment.Newline, " ");
    return SplitIntoChunks(text, 50);    
}

I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.

Solution 8 - C#

Use:

string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHcabnettekView Question on Stackoverflow
Solution 1 - C#Matt GreerView Answer on Stackoverflow
Solution 2 - C#dimazaidView Answer on Stackoverflow
Solution 3 - C#ChrisView Answer on Stackoverflow
Solution 4 - C#alonpView Answer on Stackoverflow
Solution 5 - C#vibs2006View Answer on Stackoverflow
Solution 6 - C#Fred ConklinView Answer on Stackoverflow
Solution 7 - C#Matt McClellanView Answer on Stackoverflow
Solution 8 - C#Ramya Prakash RoutView Answer on Stackoverflow