Skip to content

Instantly share code, notes, and snippets.

@kilaka
Created April 1, 2017 12:06
Show Gist options
  • Save kilaka/0206e1b7c5e2c6c3626fd457fc32950f to your computer and use it in GitHub Desktop.
Save kilaka/0206e1b7c5e2c6c3626fd457fc32950f to your computer and use it in GitHub Desktop.
/**
* Created by alik on 3/31/17.
*/
public class Main {
// TODO: Support other EndOfLines, like "\r\n".
// One way is to just replace all "\r\n" with "\n" and then run the @getLastLines method.
public static List<String> getLastLines(String string, int numLines) {
List<String> lines = new ArrayList<>();
int currentEndOfLine = string.length();
if (string.endsWith("\n")) {
currentEndOfLine = currentEndOfLine - "\n".length();
}
for (int i = 0; i < numLines; ++i) {
int lastEndOfLine = currentEndOfLine;
currentEndOfLine = string.lastIndexOf("\n", lastEndOfLine - 1);
String lastLine = string.substring(currentEndOfLine + 1, lastEndOfLine);
lines.add(0, lastLine);
}
return lines;
}
@Test
public void test1() {
String text = "111\n" +
"222\n" +
"333\n" +
"444\n" +
"555\n" +
"666\n" +
"777\n";
List<String> lastLines = getLastLines(text, 4);
Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
Assert.assertEquals(4, lastLines.size());
}
@Test
public void test2() {
String text = "111\n" +
"222\n" +
"333\n" +
"444\n" +
"555\n" +
"666\n" +
"777";
List<String> lastLines = getLastLines(text, 4);
Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
Assert.assertEquals(4, lastLines.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment