且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我们在RichTextBox中键入内容时,如何保存最后一个单词

更新时间:2023-10-29 17:56:28

int prevInd = 0;
string lastWord = "";
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    if (richTextBox1.Text.Length == 0)
        return;
    if (richTextBox1.Text[richTextBox1.Text.Length - 1] == ' ')
    {
        lastWord = richTextBox1.Text.Substring(prevInd, richTextBox1.Text.Length - prevInd);
        prevInd += lastWord.Length;
        MessageBox.Show(lastWord);
    }
}


另一种方法,

Another way,

class Program
{
    static string GetLastWord(string dataToTest)
    {
        return String.IsNullOrEmpty(dataToTest) ? default(string) : dataToTest.Split(new char[] { ' ' }).LastOrDefault();
    }

    static void Main(string[] args)
    {

        string dataToTest = "Hello world I am a String!";
        string lastWord = GetLastWord(dataToTest);
    }
}



:)



:)