String (String text, String placeholder, String replacement, List<Couple<Integer>> replacementPositions) { int curPos = 0; do { int placeholderPos = text.indexOf(placeholder, curPos); if (placeholderPos < 0) break; text = text.substring(0, placeholderPos) + replacement + text.substring(placeholderPos + placeholder.length()); ListIterator<Couple<Integer>> it = replacementPositions.listIterator(); int diff = 0; while (it.hasNext()) { Couple<Integer> next = it.next(); if (next.second > placeholderPos) { it.previous(); break; } diff = next.second - next.first; } it.add(Couple.of(placeholderPos - diff, placeholderPos)); it.add(Couple.of(placeholderPos - diff + placeholder.length(), placeholderPos + replacement.length())); while (it.hasNext()) { Couple<Integer> next = it.next(); it.set(Couple.of(next.first, next.second + replacement.length() - placeholder.length())); } curPos = placeholderPos + replacement.length(); } while (true); return text; }