Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 312
Hcabnettek Avatar asked Dec 30 '09 19:12

Hcabnettek


People also ask

Does fgets remove newline?

Removing trailing newline character from fgets() InputIt stops when either (n – 1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. However, fgets() also reads the trailing newline character and ends up returning the data string followed by '\n'.

Does fgets add newline?

The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s , adding a null character to mark the end of the string.

How do you delete a newline in a string C++?

Remove Newline characters from String using remove_if() and std::erase()

What does Strchr return?

The strchr() function returns a pointer to the first occurrence of c that is converted to a character in string.


3 Answers

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

 myString = myString.Replace("\r\n", string.Empty); 
like image 152
Matt Greer Avatar answered Sep 29 '22 18:09

Matt Greer


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

like image 44
dimazaid Avatar answered Sep 29 '22 18:09

dimazaid


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.
like image 45
Chris Avatar answered Sep 29 '22 17:09

Chris