0

I have came across this annoying feature/bug. Assume I have a string with trailing spaces like the following:

string value = "someValue    ";

The amount of spaces can vary. So I try to show it in a TextBox enclosed in begin and end tags to see how it varies, and it works perfectly.

textBox1.Text = $"BEGIN#{value}#END";

But the device that send me this value likes to add a \0 null character at the end like this:

string value = "someValue    " + Convert.ToChar(0x00);

and when I try to display it with the same method:

textBox1.Text = $"BEGIN#{value}#END;

it results in the disappearance of the #END tag. The same phenomenon happens in RichTextBox.

enter image description here

Question: Why does the null character kills/eats the rest of the string? Is it like in C or C++ that it is interpreted as the end of the char array in a string?

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • That is how Windows controls generally behave. Yes, it's like in C or C++, and your device apparently puts the `'0'` as the commonly accepted terminator which you should respect too. – GSerg Feb 20 '17 at 13:51
  • `value = value.TrimEnd('\0')` ? – spender Feb 20 '17 at 13:52
  • @GSerg no my device puts it as a bug unfortunately. So I guess I have just to adjust and take care to remove it. – Mong Zhu Feb 20 '17 at 14:12

1 Answers1

1

In some languages, such as C and C++, a null character indicates the end of a string. In the .NET Framework, a null character can be embedded in a string. When a string includes one or more null characters, they are included in the length of the total string. For example, in the following string, the substrings "abc" and "def" are separated by a null character. The Length property returns 7, which indicates that it includes the six alphabetic characters as well as the null character.

using System;
using System.Text;

public class StringClassTest
{
   public static void Main()
   {
      string characters = "abc\u0000def";
      Console.WriteLine(characters.Length);    // Displays 7
   }
}
Ahmed Salah
  • 851
  • 2
  • 10
  • 29