tags:

views:

74

answers:

1

In C# .Net I'm looking to convert an ascii value (13, 16 etc) to its escaped view (eg \n, \r, \t etc) for a selector. Is there a built in way to do this or do I have to resort to using a look up table?

+2  A: 

Not that I'm aware of... but it would be a very small lookup table anyway. It may be easiest to use a switch statement, in fact:

public static string Escape(char c)
{
    switch (c)
    {
        case '\n': return "\\n";
        case '\r': return "\\r";
        case '\t': return "\\t";
        case '\b': return "\\b";
        // etc
        default: return c.ToString(); // Perhaps...
    }
}

You could potentially also return \uxxxx for any nonprintable characters.

Jon Skeet
Those aren't verbatim strings so you'd just be passing out the unprintable character again, should either be `@"\n"` or `"\\n"`
RobV
Oops - I suspect this was written in great haste, and that I was about to fix it up but got distracted. Thanks Luke!
Jon Skeet