Monday, 5 June 2017

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




In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.



If this code:



Console.WriteLine(someString);


produces:




Hello
World!


I want this code:



Console.WriteLine(ToLiteral(someString));


to produce:




\tHello\r\n\tWorld!\r\n

Answer



I found this:



private static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{

using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.ToString();
}
}
}


This code:




var input = "\tHello\r\n\tWorld!";
Console.WriteLine(input);
Console.WriteLine(ToLiteral(input));


Produces:



    Hello
World!

"\tHello\r\n\tWorld!"

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...