c# - 从附加文本中删除第一行
问题描述
我在 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
解决方案
紧凑型
string text = this.richTextBox_message.Text;
this.richTextBox_message.Text = text.Substring(text.IndexOf('\n') + 1, text.Length - text.IndexOf('\n')-1);
解释
由于strings
are 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;
推荐阅读
- html - 使用 Bootstrap 4.2 在其他列中的两行之间拉列
- azure-active-directory - 我可以使用 AzureAD IDToken 访问 Graph API
- python - 使用 OpenCV 分隔对象计数
- javascript - 如何在 React / Javascript 中触发表单错误处理?
- ubuntu - sshd_config 通过 systemd 更改
- c++ - 有没有办法(实时)更新动态库中变量的值?
- python - cmder virtualenv 名称显示
- java - 计算机科学卡路里计算器 1
- amazon-web-services - Paws::SQS::TagQueue 失败,并显示“在未预期的位置找到列表开始”
- angular - 手动更改 URL 后未调用 ngOnInit