views:

256

answers:

3

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
A: 

Hans's code, improved version.

  1. Made it use StringBuilder - a real performance booster on long strings
  2. 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
I don't understand the down vote :)
mnn
Most probably Hans gave it to me, because his code is perfect.
Fyodor Soikin
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
A: 

System.Text.Regex.Unescape(@"\r\n\t\t\t\t\t\t\t\t\tHello world!")

Diego F.