1

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?

BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • Doesn't normal escaping, ie. @"\t\r" work or did I miss something again? – Sami May 03 '15 at 18:15
  • @Sami: I think the issue is he wants to convert the string "\t\r" to the string "\\t\\r" programatically, or e.g. "Hello\tWorld" to "Hello\\tWorld" – Eric J. May 03 '15 at 18:19
  • @Sami Exactly as Eric says. It's to be printed in the error message. – BanksySan May 03 '15 at 18:23
  • Ok. I don't understand why you want to display double backslashes, but I don't think I have to either :) – Sami May 03 '15 at 18:25
  • @Sami: Because the backslash escapes a backslash. The following are equivalent: @"\t\r" and "\\t\\r". – Eric J. May 03 '15 at 18:26
  • Exactly. I would have done something like string.Format (@"Hello{0}world", whitespaces). – Sami May 03 '15 at 18:31
  • ..and now it just hit me that you prolly don't get the whitespace chars so neatly packed as a string. So never mind :) – Sami May 03 '15 at 18:32

1 Answers1

1

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:

https://stackoverflow.com/a/324812/141172

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Performance isn't a problem yet, it's for the regression suite and only for a few cases in that. `Replace()` will do the trick I think. The OCD in me hoped there would be a more _elegant_ method. – BanksySan May 03 '15 at 18:21
  • Well write an extension method once, and then you have an elegant method :-) But I'm not aware of anything in the framework that does what you need. Leave the question open for a bit; perhaps there is something I'm not aware of. – Eric J. May 03 '15 at 18:23
  • Hey... I just found an extension method on StackOverflow that does exactly what you want. I'll close this question as a duplicate. Check out the accepted answer there. – Eric J. May 03 '15 at 18:26
  • Fair do's, that's a good spot. Cheers. – BanksySan May 03 '15 at 18:35