How to extract last word in richtextbox in c#

亡梦爱人 提交于 2019-12-13 09:48:52

问题


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.



来源:https://stackoverflow.com/questions/12431607/how-to-extract-last-word-in-richtextbox-in-c-sharp

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