0

Possible Duplicate:
Can I convert a C# string value to an escaped string literal

How can i entitize an arbitrary string to get exact human readable view similar to what the debugger does? I.e. i want all special characters entitized:

"Hello,\r\nworld"
"Hello,#D$#A$world"
"Hello,0x0D0x0Aworld"

any output like that will be fine. I'm only interested in standard function in BCL (maybe some escape routine in existing serializers or helper classes, whatever). Reverse function would be cool as well.

Community
  • 1
  • 1
UserControl
  • 14,766
  • 20
  • 100
  • 187
  • What does "entitize" mean? What would you expect the output to be? – Oded Jun 10 '12 at 10:31
  • See the output samples. I want to get a view so that i know for sure each character in the string (even non-printable). Need this for logging. – UserControl Jun 10 '12 at 10:33
  • What do you mean by "special characters"? What will you be viewing the logs in that you need escaping for? – Oded Jun 10 '12 at 10:34
  • "\n" doesn't exist at runtime, it will be a newline character. – lesderid Jun 10 '12 at 10:36
  • Thanks, lesderid! Exactly what i need. HttpUtility.JavaScriptStringEncode() does the job, though requires System.Web. Sorry for possibly confusing question. – UserControl Jun 10 '12 at 11:10
  • You should close this question as a duplicate, so when people find your question, they'll know they have to go to that question. And maybe, just maybe, you could upvote my comment. :) – lesderid Jun 10 '12 at 11:15

2 Answers2

1

I do not think that there is out of the box solution for your needs. Char.Isxxx can be used to find characters that needs special processing and custom code can replace them with info you want to see.

Code below works fine for sample but there is to many different characters in Unicode to be sure that it covers all the cases.

var s = @"Hello,
world";

var builder = new StringBuilder();

foreach (var c in s)
{
    if (Char.IsLetterOrDigit(c) || Char.IsPunctuation(c))
        builder.Append(c);
    else
    {
        var newStr = string.Format("#{0}$", ((int)c).ToString("X"));
        builder.Append(newStr);
    }
}
Console.WriteLine(builder.ToString());

Result shown in console:

Hello,#D$#A$world
Dmitry Harnitski
  • 5,838
  • 1
  • 28
  • 43
0

You can use a series of String.Replaces:

string Entitize(string input)
{
    return input.Replace("\n", "\\n").Replace("\r", "\\r"), ... ;

}
zmbq
  • 38,013
  • 14
  • 101
  • 171