How to extract last word in richtextbox in c#

2019-09-25 13:03发布

问题:

I am working with windows form. In my project i need to color the last word of rich text box. When someone write on the given text box of the application i need the last word that is just written on the richtextbox to be colored red or whatever.

I found a way to extract the last word from the following link

http://msdn.microsoft.com/en-us/library/system.windows.documents.textselection.select%28v=vs.95%29.aspx

But i need more handy code to extract the last word if its possible. Please help.

回答1:

Here is the sample code

*> char[] arr = new char[50];

      int i = 0;
    private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
     {
    if (e.KeyCode == Keys.Space)            {
        string str = new string(arr); 
        MessageBox.Show(str);
        Array.Clear(arr, 0, arr.Length);
        i = 0;
    }
    else if (e.KeyCode == Keys.Back)
       {
        i--;
        if (i < 0)
        {
            i = 0;
        }
        arr[i] = ' ';


    }

    else
    {
        arr[i] = (char)e.KeyValue;

        i++;
    }
    }*

This is how you will be able to extract the latest word. Now color yourself the word you like.



回答2:

Well, if you really are just looking to get the last word, you could do something like this...Assuming of course, that you make a string equal to the text of your rich text box.

string str="hello, how are you doing?";
if (str.Length >0)
{
    int index=str.LastIndexOf(" ") + 1;
    str = str.Substring(index));
}

Then just return the string, and do what you need to do with it.



回答3:

As I remember rich text box can render text as HTML.
Just wrap your last word in font tag and that's it.