Scanner { public CharSequence textBetween(Position begin, Position end) { if (begin.lineIndex == end.lineIndex) { return lines.get(begin.lineIndex).subSequence(begin.index, end.index); } else { StringBuilder sb = new StringBuilder(); CharSequence firstLine = lines.get(begin.lineIndex); sb.append(firstLine.subSequence(begin.index, firstLine.length())); sb.append('\n'); for (int line = begin.lineIndex + 1; line < end.lineIndex; line++) { sb.append(lines.get(line)); sb.append('\n'); } CharSequence lastLine = lines.get(end.lineIndex); sb.append(lastLine.subSequence(0, end.index)); return sb.toString(); } } Scanner(List<CharSequence> lines, int lineIndex, int index); static Scanner of(List<CharSequence> lines); static Scanner of(CharSequence line); char peek(); char peekPrevious(); boolean hasNext(); void next(); boolean next(char c); boolean next(String content); int matchMultiple(char c); int match(CharMatcher matcher); int whitespace(); int find(char c); int find(CharMatcher matcher); Position position(); void setPosition(Position position); CharSequence textBetween(Position begin, Position end); static final char END; }
@Test public void testTextBetween() { Scanner scanner = new Scanner(Arrays.<CharSequence>asList("ab", "cde"), 0, 0); Position start = scanner.position(); scanner.next(); assertEquals("a", scanner.textBetween(start, scanner.position())); Position afterA = scanner.position(); scanner.next(); assertEquals("ab", scanner.textBetween(start, scanner.position())); scanner.next(); assertEquals("ab\n", scanner.textBetween(start, scanner.position())); scanner.next(); assertEquals("ab\nc", scanner.textBetween(start, scanner.position())); scanner.next(); assertEquals("ab\ncd", scanner.textBetween(start, scanner.position())); scanner.next(); assertEquals("ab\ncde", scanner.textBetween(start, scanner.position())); assertEquals("b\ncde", scanner.textBetween(afterA, scanner.position())); }