删除富文本框的最后一行?

时间:2014-03-23 05:36:34

标签: c# regex substring stringbuilder

我想删除已结束的richtextbox的最后一行; semicolumn。我喜欢删除此行,直到;在最后一个半圆之前出现的半圆。

示例:

hello do not delete this line;
hello this sentence will continue...
untill here;

结果应为:

hello do not delete this line;

我的代码:

private void button1_Click_1(object sender, EventArgs e) {
        List<string> myList = richTextBox1.Lines.ToList();
        if (myList.Count > 0) {
            myList.RemoveAt(myList.Count - 1);
            richTextBox1.Lines = myList.ToArray();
            richTextBox1.Refresh();
        }
    }

6 个答案:

答案 0 :(得分:1)

使用此:

var last = richTextBox1.Text.LastIndexOf(";");
if (last > 0)
{
   richTextBox1.Text = richTextBox1.Text.Substring(0, last - 1);
   var beforelast = richTextBox1.Text.LastIndexOf(";");
   richTextBox1.Text = richTextBox1.Text.Substring(0, beforelast + 1);
}
else
{
   richTextBox1.Text = "";
}

您未指定其他方案(即,字符串不包含&#34;;&#34;) 此代码删除从&#34;;&#34;开始的字符串。就在最后一次&#34;;&#34;到最后&#34;;&#34;。 它删除了最后一个分号和文本,然后找到新的最后一个&#34 ;;&#34;。最后删除文本&#34;;&#34;

答案 1 :(得分:1)

找到解决方案here

RichTextBox1.Lines = RichTextBox1.Lines.Take(RichTextBox1.Lines.Length - 3).ToArray();

答案 2 :(得分:1)

对于那些在这些年后发现这个问题的人......

使用.Text属性或.Lines属性的解决方案最终会从现有文本中删除格式。而是使用这样的东西来保留格式:

var i = textBox.Text.LastIndexOf("\n");
textBox.SelectionStart = i;
textBox.SelectionLength = o.TextLength - i + 1;
textBox.SelectedText = "";

请注意,如果您的文本框处于ReadOnly模式,则无法修改SelectedText。在这种情况下,您需要像这样设置和重置ReadOnly:

textBox.ReadOnly = false;
textBox.SelectedText = "";
textBox.ReadOnly = true;

答案 3 :(得分:0)

我不确定富文本框是如何工作的,但是

input = {rich text box text}
int index = text.lastIndexOf(";");
if (index > 0) 
{
    input = input.Substring(0, index);
}

// put input back in text box

答案 4 :(得分:0)

int totalcharacters = yourrtb.Text.Trim().Length;
int totalLines = yourrtb.Lines.Length;
string lastLine = yourrtb.Lines[totalLines - 1];
int lastlinecharacters = lastLine.Trim().Length;
yourrtb.Text = yourrtb.Text.Substring(0, totalcharacters - lastlinecharacters);

答案 5 :(得分:0)

那怎么样?

string input = "your complete string; Containing two sentences";

List<string> sentences = s.Split(';').ToList();

//Delete the last sentence
sentences.Remove(sentences[sentences.Count - 1]);

string result = string.Join(" ", sentences.ToArray());
相关问题