I have a string which I am sending to an external print function.
I need to pad the string with backslashes so it prints properly.
Specifically, I need a method which would accept this example input:This is a string\nwith a line break\ta tab\rand a carriage return.
and output:This is a string\\nwith a line break\\ta tab\\rand a carriage return.
Do I need to brute force Replace
every possible escape character with it's backslashed equivalent?
Tried:s.Replace("\\","\\\\")
Doesn't work because it's looking for a backslash literal.
s.Replace("\n","\\n")
obviously works, but what I'm looking for is a generic method.
Edit: Please don't suggest brute force methods, I understand it is no problem to implement such a method. My question was if there is a more universal approach.
private static string EscapeLiterals(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.ToString();
}
}
}
Takes input "\tHello\r\n\tLiterals!"
and turns it into "\\tHello\\r\\n\\tLiterals!"
Works for any input - it will get you the escape sequence for anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With