Program to print last N lines | Set-2

• Difficulty Level : Medium
• Last Updated : 28 Jan, 2020

Given some text lines in one string, each line is separated by â€˜\nâ€™ character. Print the last N lines. If the number of lines is less than N, then print all lines.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

An approach for this problem has been already discussed in Set-1 where only 10 lines were printed. In this post, another approach is discussed for printing the last N lines.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Algorithm:

• Split the string around ‘\n’ using strtok.
• Store the individual strings in a vector.
• Print the last N strings from vector.

Below is the implementation of the above approach:

C++

 `// C++ program to print the last N lines``#include ``using` `namespace` `std;`` ` `void` `PrintLast(string s, ``int` `t)``{``    ``// Vector to store individual strings.``    ``vector v;`` ` `    ``// Get a pointer to string.``    ``char``* str = &s[0];``    ``// Split the string around '\n'.``    ``char``* token = ``strtok``(str, ``"\n"``);`` ` `    ``// Save all strings in the vector.``    ``while` `(token) {``        ``v.push_back(token);``        ``token = ``strtok``(NULL, ``"\n"``);``    ``}`` ` `    ``if` `(v.empty()) {``        ``cout << ``"ERROR: string doesn't contain '\\n' character\n"``;``        ``return``;``    ``}`` ` `    ``// If the string has t lines``    ``if` `(v.size() >= t) {``        ``for` `(``int` `i = v.size() - t; i < v.size(); i++)``            ``cout << v[i] << endl;``    ``}``    ``else` `{``        ``for` `(``int` `i = 0; i < v.size(); i++)``            ``cout << v[i] << endl;``    ``}``}`` ` `// Driver Code``int` `main()``{``    ``string s1 = ``"str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7\nstr8\nstr9"``                ``"\nstr10\nstr11\nstr12\nstr13\nstr14\nstr15\nstr16\nstr17"``                ``"\nstr18\nstr19\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25"``;``    ``int` `n = 10;``    ``PrintLast(s1, n);`` ` `    ``return` `0;``}`

Java

 `// Java program to print the last N lines``import` `java.util.*;`` ` `class` `GFG ``{``    ``static` `void` `printLast(String s, ``int` `t)``    ``{`` ` `        ``// Vector to store individual strings.``        ``// Save all strings in the vector.``        ``String[] v = s.split(``"\n"``);`` ` `        ``if` `(v.length == ``0``) ``        ``{``            ``System.out.println(``"ERROR: string doesn't "` `+ ``                              ``"contain '\\n' character"``);``            ``return``;``        ``}`` ` `        ``// If the string has t lines``        ``if` `(v.length >= t) ``        ``{``            ``for` `(``int` `i = v.length - t; i < v.length; i++)``            ``{``                ``System.out.println(v[i]);``            ``}``        ``} ``        ``else` `        ``{``            ``for` `(``int` `i = ``0``; i < v.length; i++)``            ``{``                ``System.out.println(v[i]);``            ``}``        ``}``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args) ``    ``{``        ``String s1 = ``"str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7"` `+ ``                    ``"\nstr8\nstr9\nstr10\nstr11\nstr12\nstr13"` `+ ``                    ``"\nstr14\nstr15\nstr16\nstr17\nstr18\nstr19"` `+ ``                    ``"\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25"``;``        ``int` `n = ``10``;``        ``printLast(s1, n);``    ``}``}`` ` `// This code is contributed by``// sanjeev2552`

Python3

 `# Python3 program to print the last N lines ``def` `PrintLast(s, t): `` ` `    ``# Vector to store individual strings. ``    ``v ``=` `s.split(``'\n'``)``     ` `    ``if` `len``(v) ``=``=` `0``: ``        ``print``(``"ERROR: string doesn't "``,``              ``"contain '\\n' character\n"``) ``        ``return``     ` `    ``# If the string has t lines ``    ``elif` `len``(v) >``=` `t: ``        ``for` `i ``in` `range``(``len``(v) ``-` `t, ``len``(v)): ``            ``print``(v[i]) ``     ` `    ``else``:``        ``for` `i ``in` `range``(``0``, ``len``(v)): ``            ``print``(v[i])``     ` `# Driver Code ``if` `__name__ ``=``=` `"__main__"``:`` ` `    ``s1 ``=` `"str1\nstr2\nstr3\nstr4\nstr5\nstr6"` `+` `\``         ``"\nstr7\nstr8\nstr9\nstr10\nstr11"` `+` `\``         ``"\nstr12\nstr13\nstr14\nstr15\nstr16"` `+` `\``         ``"\nstr17\nstr18\nstr19\nstr20\nstr21"` `+` `\``         ``"\nstr22\nstr23\nstr24\nstr25"``     ` `    ``n ``=` `10``    ``PrintLast(s1, n) `` ` `# This code is contributed by Rituraj Jain`

C#

 `// C# program to print the last N lines``using` `System;`` ` `class` `GFG ``{``    ``static` `void` `printLast(String s, ``int` `t)``    ``{`` ` `        ``// List to store individual strings.``        ``// Save all strings in the vector.``        ``String[] v = s.Split(``'\n'``);`` ` `        ``if` `(v.Length == 0) ``        ``{``            ``Console.WriteLine(``"ERROR: string doesn't "` `+ ``                            ``"contain '\\n' character"``);``            ``return``;``        ``}`` ` `        ``// If the string has t lines``        ``if` `(v.Length >= t) ``        ``{``            ``for` `(``int` `i = v.Length - t; i < v.Length; i++)``            ``{``                ``Console.WriteLine(v[i]);``            ``}``        ``} ``        ``else``        ``{``            ``for` `(``int` `i = 0; i < v.Length; i++)``            ``{``                ``Console.WriteLine(v[i]);``            ``}``        ``}``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `Main(String[] args) ``    ``{``        ``String s1 = ``"str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7"` `+ ``                    ``"\nstr8\nstr9\nstr10\nstr11\nstr12\nstr13"` `+ ``                    ``"\nstr14\nstr15\nstr16\nstr17\nstr18\nstr19"` `+ ``                    ``"\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25"``;``        ``int` `n = 10;``        ``printLast(s1, n);``    ``}``}`` ` `// This code is contributed by Rajput-Ji`
Output:
```str16
str17
str18
str19
str20
str21
str22
str23
str24
str25
```

My Personal Notes arrow_drop_up