Get the last word entered in RichTextBox c#

隐身守侯 提交于 2020-01-05 05:54:04

问题


How do I get the last word entered(the word between two space characters or it should take into account the new line,paragraph or tab chracters) and its start position and end position in a Winform RichTextBox using c#. I need to get the last word as soon as I press space key

My code ( not working properly):

 private Word GetLastEnteredWord()
    {

        string _word = " ";
        int pos = rtfText.SelectionStart;
         Word word=new Word(_word,pos,0);
        if (pos > 1)
        {
            string tmp = "";
            var f = new char();
            while (f != ' ' && f != 10 && pos > 0)
            {
                pos--;
                tmp = rtfText.Text.Substring(pos, 1);

                    f = tmp[0];
                    _word += f;


            }

            char[] ca = _word.ToCharArray();
            Array.Reverse(ca);
            _word = new String(ca);
            word.RWord = _word;
            word.Si = pos;
            word.Length = _word.Length;


        }

        return word;
    }


 public class Word
{
    public Word(string word, int starti, int len)
    {
        RWord = word; //word
        Si = starti; //start index
        Length = len;
    }

    public string RWord { get; set; }
    public int Si { get; set; }
    public int Length { get; set; }
}

回答1:


Just do a trivial trick with Substring() method:

//KeyPress event handler for your richTextBox
private void richTextBox_KeyPress(object sender, KeyPressEventArgs e){
   if(e.KeyChar == ' '){
     int i = richTextBox.Text.TrimEnd().LastIndexOf(' ');
     if(i != -1) MessageBox.Show(richTextBox.Text.Substring(i+1).TrimEnd());
   }
}



回答2:


This should be enough

 string lastWord = richTextBox1.Text.TrimEnd().Substring(richTextBox1.Text.TrimEnd()
            .LastIndexOf(' ')).Trim();


来源:https://stackoverflow.com/questions/18222988/get-the-last-word-entered-in-richtextbox-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!