0

I have no idea how to show weird character code. example \n, \u0003. I want to show it "\n" or "\u0003" on textbox, i.e. I don't want to show the symbol itself but its code.

any idea?

thank you so much

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Those aren't "weird" characters, they are escape sequences for characters in the 7-bit US-ASCII range. The first one is just a newline. The second one is the *non*-printable `End of Text` character. Just include those escape sequences in your strings, but don't expect to see anything - they are *non*printable – Panagiotis Kanavos Dec 24 '19 at 08:35
  • By default, text boxes have only a single line and newlines don't affect how the contents look. If you want to display the text in multiple lines, you'll have to set the `Multiline` property to `true` – Panagiotis Kanavos Dec 24 '19 at 08:39
  • The FAQ article [What character escape sequences are available?](https://devblogs.microsoft.com/csharpfaq/what-character-escape-sequences-are-available/) shows the available escape sequences for C# – Panagiotis Kanavos Dec 24 '19 at 08:40
  • If you want to *show* `\n`, `textBox1.Text = "\\n";`, if you want to *print* the corresponding Unicode char, remove one slash (e.g., `textBox1.Text = "\u277D";`). Characters with *special* meaning, as `\n` (not `"\u0010"`), will be *treated* accordingly. – Jimi Dec 24 '19 at 08:41
  • [Convert a C# string value to an escaped string literal](https://stackoverflow.com/q/323640/3110834). – Reza Aghaei Dec 24 '19 at 08:54

1 Answers1

1

If you want to encode the string, i.e. to represent control characters with their codes (for instance for some kind of logging, debugging etc.)

  using System.Linq;

  ...

  private static string Encode(string value) {
    if (null == value)
      return null;

    return string.Concat(value
      .Select(c => char.IsControl(c) 
         ? $"\\u{((int) c):x4}" // control symbol - as a code
         : c.ToString()));      // non-control    - as it is
  }

Then

  myTextBox.Text = Encode("abc\ndef\r\t566");

And you'll have

  abc\u000adef\u000d\u0009566
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215