AlignedString implements Iterable<AlignedString.DataSegment> { public void replace(final int start, final int end, final String d) { if (start == end) { insert(start, d); return; } final AbstractDataSegment segAtStart = getSegmentAt(start); final AbstractDataSegment segAtEnd = getSegmentAt(end - 1, end > 1); AbstractDataSegment prefix; AbstractDataSegment suffix; if (segAtStart == segAtEnd) { prefix = segAtStart; prefix.split(start); suffix = prefix._next; suffix = suffix.split(end); if (d == null || d.length() == 0) { prefix._next = suffix; suffix._prev = prefix; } else { final BaseSegment s = new BaseSegment(prefix, suffix, d); prefix._next = s; suffix._prev = s; } } else { if (d == null || d.length() == 0) { AbstractDataSegment s = segAtStart; while (s != segAtEnd) { if (s.isAnchor()) { throw new UnsupportedOperationException( "Unable to replace text containing anchors."); } s = s._next; } } segAtStart.split(start); prefix = segAtStart; suffix = segAtEnd.split(end); if (d == null || d.length() == 0) { AbstractDataSegment s = prefix._next; while (s != suffix) { if (s.isAnchor()) { } else { s._prev._next = s._next; s._next._prev = s._prev; } s = s._next; } } else { final BaseSegment s = new BaseSegment(prefix, suffix, d); prefix._next = s; suffix._prev = s; } } dropSuperflourous(prefix); dropSuperflourous(suffix); fireChange(); } private  AlignedString();  AlignedString(final String base);  AlignedString(final AlignedString underlying); void fireChange(); Interval resolve(final Interval i); ImmutableInterval inverseResolve(final ImmutableInterval i); AbstractDataSegment getSegmentAt(final int position); AbstractDataSegment getFirst(); AbstractDataSegment getLast(); @Override Iterator<DataSegment> iterator(); int length(); String get(); void updateCaches(); String get(final int start, final int end); void insert(final int pos, final String s); void delete(final int start, final int end); void replace(final int start, final int end, final String d); Anchor getAnchor(final int pos); Collection<Anchor> getAnchors(); Collection<DataSegment> getSegments(); String dataSegmentsToString(); @Override String toString();  }
@Test public void testReplace() { top.replace(2, 4, "want"); final StringBuilder topRef = new StringBuilder(baseString); topRef.replace(2,4,"want"); assertEquals(topRef.toString(), top.get()); }