Simple question : how to strip carriage returns from a string?

  • Thread starter Thread starter Howard Dean
  • Start date Start date
H

Howard Dean

I have a string with several carriage returns in it. For example:

"This is
my test
string"

I wish to convert it to "This is my test string" (remove all carriage
returns. Can someone tell me how to do this using the string.Replace
function? Thanks!
 
You really should check for/replace ASCII 10 and 13 (Carrier Return and Line
Feed)
In C#: \r and \n

i.e.

s = s.Replace("\n","").Replace("\r","");

OR if you want to replace several chars you can use the overload for .Trim
and build a unicode array of the chars to remove instead of piling up
..Replaces
 
string pattern = @"[\n\r]";
string fixupPattern = @"\x20{2,}?";
string source = "this\n\ris a\r\ntest of\n\rsomething";

Console.WriteLine( "Source:\n{0}", source );
Regex r = new Regex( pattern, RegexOptions.Singleline );
string newtext = r.Replace( source, "\x20" );
Regex fixup = new Regex( fixupPattern );
newtext = fixup.Replace( newtext, "\x20" );

Console.WriteLine( "New Text:\n{0}", newtext );

This could probably be condensed to one regex.
 
Back
Top