I have a string of assorted white-space: e.g.
"\t\r "
I need to display it in an error message, but just showing white-space isn't helpful.
Is there a method to encode the string for displaying?
I have a string of assorted white-space: e.g.
"\t\r "
I need to display it in an error message, but just showing white-space isn't helpful.
Is there a method to encode the string for displaying?
If you don't specifically need the C# escaping convention, you can URL encode the string. That will provide a visible encoding for non-printable and whitespace characters. For a table comparing the output of various encoding options, see
https://stackoverflow.com/a/11236038/141172
If you do need the C# escaping convention, you could do something as simple as
string output = original.Replace("\t", "\\t").Replace("\r", "\\r); // etc
If this is for occasionally outputting an error message, the inefficiency of creating a new string for each call to .Replace will not matter. If it does matter, you could create a method / an extension method that loops through each character in the input string and outputs either the original character, or an escaped version, as appropriate (e.g. using StringBuilder to build up the output string).
UPDATE
Here's an extension method that does exactly what you want: