Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

take the last n lines of a string c#

I have a string of unknown length

it is in the format

\nline
\nline
\nline

with out know how long it is how can i just take the last 10 lines of the string a line being separated by "\n"

like image 747
user1588670 Avatar asked Aug 13 '12 21:08

user1588670


4 Answers

As the string gets larger, it becomes more important to avoid processing characters that don't matter. Any approach using string.Split is inefficient, as the whole string will have to be processed. An efficient solution will have to run through the string from the back. Here's a regular expression approach.

Note that it returns a List<string>, because the results need to be reversed before they're returned (hence the use of the Insert method)

private static List<string> TakeLastLines(string text, int count)
{
    List<string> lines = new List<string>();
    Match match = Regex.Match(text, "^.*$", RegexOptions.Multiline | RegexOptions.RightToLeft);

    while (match.Success && lines.Count < count)
    {
        lines.Insert(0, match.Value);
        match = match.NextMatch();
    }

    return lines;
}
like image 86
Simon MᶜKenzie Avatar answered Nov 18 '22 23:11

Simon MᶜKenzie


var result = text.Split('\n').Reverse().Take(10).ToArray();
like image 29
Volma Avatar answered Nov 19 '22 01:11

Volma


Split() the string on \n, and take the last 10 elements of the resulting array.

like image 6
Robert Harvey Avatar answered Nov 19 '22 01:11

Robert Harvey


If this is in a file and the file is particularly large, you may want to do this efficiently. A way to do it is to read the file backwards, and then only take the first 10 lines. You can see an example of using Jon Skeet's MiscUtil library to do this here.

var lines = new ReverseLineReader(filename);
var last = lines.Take(10);
like image 3
yamen Avatar answered Nov 19 '22 00:11

yamen