Overlays part of a String with another String.
* *A null
string input returns null
.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.
* StringUtils.overlay(null, *, *, *) = null * StringUtils.overlay("", "abc", 0, 0) = "abc" * StringUtils.overlay("abcdef", null, 2, 4) = "abef" * StringUtils.overlay("abcdef", "", 2, 4) = "abef" * StringUtils.overlay("abcdef", "", 4, 2) = "abef" * StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef" * StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef" * StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef" * StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz" * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef" * StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz" ** * @param str the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at * @param end the position to stop overlaying before * @return overlayed String,
null
if null String input
* @since 2.0
*/
public static String overlay(String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = "";
}
int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
int temp = start;
start = end;
end = temp;
}
return new StringBuffer(len + start - end + overlay.length() + 1)
.append(str.substring(0, start))
.append(overlay)
.append(str.substring(end))
.toString();
}
}