I need a textbox on a WPF control that can take in text like "Commit\r\n\r" (which is the .net string "Commit\r\n\r") and convert it back to "Commit\r\n\r" as a .net string. I was hoping for a string.Unescape() and string.Escape() method pair, but it doesn't seem to exist. Am I going to have to write my own? or is there a more simple way to do this?
A:
So is your problem that you are trying to convert to and from ASCII? Because it's not at all clear what you want to "escape" or "unescape".
Encoding.ASCII will return an encoding object that you can use to convert between Unicode and ASCII (GetBytes to convert to ASCII from a .Net String,, GetString to convert from an array of ASCII bytes to a string ).
JasonTrue
2010-04-18 04:52:10
A:
Hans's code, improved version.
- Made it use StringBuilder - a real performance booster on long strings
Made it an extension method
public static class StringEscape { public static string EscapeStringChars( this string txt ) { if ( string.IsNullOrEmpty( txt ) ) return txt;
}StringBuilder retval = new StringBuilder( txt.Length ); for ( int ix = 0; ix < txt.Length; ) { int jx = txt.IndexOf( '\\', ix ); if ( jx < 0 || jx == txt.Length - 1 ) jx = txt.Length; retval.Append( txt, ix, jx-ix ); if ( jx >= txt.Length ) break; switch ( txt[jx + 1] ) { case 'n': retval.Append( '\n' ); break; // Line feed case 'r': retval.Append( '\r' ); break; // Carriage return case 't': retval.Append( '\t' ); break; // Tab case '\\': retval.Append( '\\' ); break; // Don't escape default: // Unrecognized, copy as-is retval.Append( '\\' ).Append( txt[jx + 1] ); break; } ix = jx + 2; } return retval.ToString(); }
Fyodor Soikin
2010-04-18 11:16:31
I don't understand the down vote :)
mnn
2010-04-18 15:03:24
Most probably Hans gave it to me, because his code is perfect.
Fyodor Soikin
2010-04-18 17:45:43
You are quite a piece of work. Certainly not worth the down-vote penalty. I'm quite sorry I helped you, I promise it won't happen again.
Hans Passant
2010-04-18 18:42:52