Program to print the last N lines

Coding Sep 12, 2020

Introduction

Given the string, we have to print the last N lines (known problem to print last 10 lines). If number of lines is less than N, then print all lines. This problem statement is asked by Microsoft.

Approach

We can find the last occurence of the newline character and then decreement the position to find the next n occurences.

Approach Deduction Logic
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    public class PrintLastNOccurence
    {
        public static void Run()
        {
            var p = new PrintLastNOccurence();
            Console.WriteLine(p.GetLastNOccurence("abc\ndef\ng\nh\ni\nj\nk\nl\nm\nn\nq", '\n', 5));
        }
        public string GetLastNOccurence(string s, char delimiter, int n)
        {
            var pos = s.LastIndexOf(delimiter);
            if (pos == -1)
            {
                throw new KeyNotFoundException($"{delimiter} character is not found in the {s}");
            }
            
            while (n-- > 1 && pos-- != -1)
            {
                while (pos >= 0 && s[pos] != delimiter)
                {
                    pos--;
                }
            }

            return s.Substring(pos + 1);
        }
    }
}