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.
// C++ Program to print the last 10 lines.
// If number of lines is less than 10,
// then print all lines.
#define DELIM '\n'
/* Function to print last n lines of a given string */
/* Base case */
if(n <= 0)
size_tcnt = 0; // To store count of '\n' or DELIM
char*target_pos = NULL; // To store the output position in str
/* Step 1: Find the last occurrence of DELIM or '\n' */
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.
Please Login to comment...