获取在 RichTextBox c# 中输入的最后一个单词 [英] Get the last word entered in RichTextBox c#

查看:65
本文介绍了获取在 RichTextBox c# 中输入的最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 c# 在 Winform RichTextBox 中输入最后一个单词(两个空格字符之间的单词,或者它应该考虑新行、段落或制表符)及其开始位置和结束位置.我需要按空格键就得到最后一个字

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

推荐答案

只需使用 Substring() 方法做一个小技巧:

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());
   }
}

这篇关于获取在 RichTextBox c# 中输入的最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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