Created
April 1, 2017 12:06
-
-
Save kilaka/0206e1b7c5e2c6c3626fd457fc32950f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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