take the last n lines of a string c#

user1588670 picture user1588670 · Aug 13, 2012 · Viewed 8.3k times · Source

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"

Answer

Simon MᶜKenzie picture Simon MᶜKenzie · Aug 14, 2012

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;
}