Open In App

Program to print last N lines | Set-2

Improve
Improve
Like Article
Like
Save
Share
Report

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.

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. 

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 <bits/stdc++.h>
using namespace std;
 
void PrintLast(string s, int t)
{
    // Vector to store individual strings.
    vector<string> 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


Javascript




function PrintLast( s, t)
{
     
    const v = s.split("\n");
    if (v.length==0) {
        console.log( "ERROR: string doesn't contain '\\n' character\n");
        return;
    }
 
    // If the string has t lines
    if (v.length >= t) {
        for (let i = v.length - t; i < v.length; i++)
            console.log(v[i]);
    }
    else {
        for (let i = 0; i < v.length; i++)
            console.log(v[i]);
    }
}
 
    let 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";
    let n = 10;
    PrintLast(s1, n);
 
    // This code is contributed by garg28harsh.


Output

str16
str17
str18
str19
str20
str21
str22
str23
str24
str25

Time Complexity: O(n)
Auxiliary Space: O(n)



Last Updated : 22 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads