Given some text lines in one string, each line is separated by ‘\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines.
Source: Microsoft Interview | Set 10
Following are the steps
1) Find the last occurrence of DELIM or ‘\n’
2) Initialize target position as last occurrence of ‘\n’ and count as 0 , and do following while count < 10
……2.a) Find the next instance of ‘\n’ and update target position
…..2.b) Skip ‘\n’ and increment count of ‘\n’ and update target position
3) Print the sub-string from target position.
str16 str17 str18 str19 str20 str21 str22 str23 str24 str25 ----------------- str1 str2 str3 str4 str5 str6 str7 ----------------- ----------------- ERROR: string doesn't contain '\n' character -----------------
Note: Above program can be modified to print last N lines by passing N instead of 10. N can store any integer value.
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Implement your own tail (Read last n lines of a huge file)
- Print 2D matrix in different lines and without curly braces in C/C++?
- C Program to count number of lines in a file
- Lex program to take input from file and remove multiple spaces, lines and tabs
- Lex program to count the number of lines, spaces and tabs
- How to use getline() in C++ when there are blank lines in input?
- How to write long strings in Multi-lines C/C++?
- C program to print a string without any quote (singe or double) in the program
- Last element of vector in C++ (Accessing and updating)
- Get first and last elements from Array and Vector in CPP
- How to delete last element from a map in C++
- How to delete last element from a List in C++ STL
- Write a C program to print "Geeks for Geeks" without using a semicolon
- Program to print the diamond shape
- Program to print Happy Birthday
- C Program to print numbers from 1 to N without using semicolon?
- Program to print a pattern of numbers
- C Program to print environment variables
- C Program to print contents of file
- C Program to print Floyd's triangle
Improved By : rathbhupendra