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.

6
  • What does "entitize" mean? What would you expect the output to be? Commented Jun 10, 2012 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. Commented Jun 10, 2012 at 10:33
  • What do you mean by "special characters"? What will you be viewing the logs in that you need escaping for? Commented Jun 10, 2012 at 10:34
  • "\n" doesn't exist at runtime, it will be a newline character. Commented Jun 10, 2012 at 10:36
  • Thanks, lesderid! Exactly what i need. HttpUtility.JavaScriptStringEncode() does the job, though requires System.Web. Sorry for possibly confusing question. Commented Jun 10, 2012 at 11:10

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a series of String.Replaces:

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

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.