空字符删除 TextBox 和 RichTextBox 中的其余输出 [英] Null character deleting rest of output in TextBox and RichTextBox

查看:28
本文介绍了空字符删除 TextBox 和 RichTextBox 中的其余输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个烦人的功能/错误.假设我有一个带有尾随空格的字符串,如下所示:

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

string value = "someValue    ";

空格的数量可能会有所不同.因此,我尝试将它显示在包含在开始和结束标记中的 TextBox 中,以查看它如何变化,并且它完美地工作.

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";

但是向我发送这个值的设备喜欢在末尾添加一个 \0 空字符,如下所示:

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;

它会导致 #END 标签消失.同样的现象发生在 RichTextBox 中.

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

问题:为什么空字符会杀死/吃掉字符串的其余部分?是否像在 C 或 C++ 中被解释为字符串中 char 数组的结尾?

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?

推荐答案

在某些语言(例如 C 和 C++)中,空字符表示字符串的结尾.在 .NET Framework 中,可以在字符串中嵌入空字符.当一个字符串包含一个或多个空字符时,它们包含在整个字符串的长度中.例如,在以下字符串中,子字符串abc"和def"由空字符分隔.Length 属性返回 7,表示它包括六个字母字符以及空字符.

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
   }
}

这篇关于空字符删除 TextBox 和 RichTextBox 中的其余输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆