How to read the last line in a textbox?

时光毁灭记忆、已成空白 提交于 2019-12-01 03:44:04

问题


I have a multiline textbox that constantly gets updated. I need to read only the last word/sentence in the textbox.

string lastLine = textBox1.ReadLine.Last();

回答1:


Try this:

if (textBox1.Lines.Any())
{
    string lastLine = textBox1.Lines[textBox1.Lines.Length - 1];
}

And for last word:

string lastword = lastLine.Split(' ').Last();



回答2:


You can extract the last line from any string as follows:

string str = ....;

string[] lines = str.Split('\n', '\r');
string last_line = lines[lines.Length - 1];

To get the last line of a TextBox you can use:

string[] lines = textBox1.Text.Split('\n', '\r');
string last_line = lines[lines.Length - 1];



回答3:


A textbox with the MultiLine property set to true has an array of Lines from which it is easy to extract the info required

int maxLines = textBox1.Lines.Length;
if(maxLines > 0)
{
    string lastLine = textBox1.Lines[maxLines-1];
    string lastWord = lastLine.Split(' ').Last();
}

A bit of caution here is needed. If your textBox still doesn't contain any lines you need to introduce a check on the number of lines present



来源:https://stackoverflow.com/questions/32924410/how-to-read-the-last-line-in-a-textbox

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