首页 > 解决方案 > 从附加文本中删除第一行

问题描述

我在 Visual Studio 中处理我的richtextbox。我附加了来自串行接口(uart)的通信。

但是在 ~1000 行之后,我想删除第一行。

但这应该如何工作?

我试过了:

this.richTextBox_message.Text.Remove(0, 1000);      // doesn't work
                                                    // would be bad solution, because i want to remove lines and not chars,
this.richTextBox_message.Select(0, 100);
this.richTextBox_message.SelectedText.Remove(1);    // doesn't work

标签: c#user-interfacerichtextbox

解决方案


紧凑型

string text = this.richTextBox_message.Text;
this.richTextBox_message.Text = text.Substring(text.IndexOf('\n') + 1, text.Length - text.IndexOf('\n')-1);

解释

由于stringsare immutable,我们必须创建一个string没有第一行的新文本并将文本框的文本设置为该文本。

让我们首先获取文本的副本,这样我们就不必一直写this.richTextBox_message.Text

string text = this.richTextBox_message.Text;

我们可以使用该Substring方法来获取没有第一行的字符串的版本。为了做到这一点,我们必须知道从哪里开始以及我们想要抓取多少个角色。Substring(int index, int length).

我们可以使用IndexOf来查找文本中第一次出现的行分隔符。那将是该行的终点。然后我们想要添加 1 以在我们的新文本中不包含行分隔符。

int startIndex = text.Substring(text.IndexOf('\n') + 1;

现在我们需要找到我们想要获取的文本的长度。这很简单——我们想要从刚刚找到的 startIndex 到文本末尾的所有文本。我们可以从文本长度中减去 startIndex 得到我们想要的长度。

int length = text.Length - startIndex;

现在我们可以得到新的字符串了。

string newValue = text.Substring(startIndex, length);

最后将其写回 text 属性。

this.richTextBox_message.Text = newValue;

推荐阅读