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

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!
 
C

Craig S

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
 
C

Chris Hornberger

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top