Search code examples
c#stringstring-parsing

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"


Solution

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