Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last line in simple string variable - C#

Tags:

string

c#

I have a simple string variable as follows and I want to get last line from this text.

string mytext ="line1\nline2\nline3";

Please do not offer to use

var lastLine = File.ReadLines("file.txt").Last();

Because the target string is not stored in the file.

Thanks for your help

like image 386
Mahyar Esteki Avatar asked Oct 14 '25 14:10

Mahyar Esteki


2 Answers

Split by newline and then do last:

var lastLine = mytext.Split('\n').Last();
like image 149
Hatted Rooster Avatar answered Oct 17 '25 04:10

Hatted Rooster


Try this:

int idx = mytext.LastIndexOf('\n');

if (idx != -1)
{
    var rsult = mytext.Substring(idx + 1);
}
like image 31
Hasan Fathi Avatar answered Oct 17 '25 04:10

Hasan Fathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!