diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index ee6b9eea7ef..5080e610042 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -370,11 +370,8 @@ public static String abbreviate(final String str, String abbrevMarker, int offse if (strLen <= maxWidth) { return str; } - if (offset > strLen) { - offset = strLen; - } - if (strLen - offset < maxWidth - abbrevMarkerLength) { - offset = strLen - (maxWidth - abbrevMarkerLength); + if (strLen - offset <= maxWidth - abbrevMarkerLength) { + return abbrevMarker + str.substring(strLen - (maxWidth - abbrevMarkerLength)); } if (offset <= abbrevMarkerLength + 1) { return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker; @@ -382,10 +379,7 @@ public static String abbreviate(final String str, String abbrevMarker, int offse if (maxWidth < minAbbrevWidthOffset) { throw new IllegalArgumentException(String.format("Minimum abbreviation width with offset is %d", minAbbrevWidthOffset)); } - if (offset + maxWidth - abbrevMarkerLength < strLen) { - return abbrevMarker + abbreviate(str.substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength); - } - return abbrevMarker + str.substring(strLen - (maxWidth - abbrevMarkerLength)); + return abbrevMarker + abbreviate(str.substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength); } /** diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java index 8ef0cfc855c..cf947ee111c 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java @@ -101,6 +101,8 @@ void testAbbreviate_StringIntInt() { assertAbbreviateWithOffset("...ijklmno", 15, 10); assertAbbreviateWithOffset("...ijklmno", 16, 10); assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10); + // abbreviating a shorter string allows maxWidth < 7 + assertEquals("...efg", StringUtils.abbreviate("abcdefg", 5, 6)); } @Test @@ -163,6 +165,9 @@ void testAbbreviate_StringStringIntInt() { assertAbbreviateWithAbbrevMarkerAndOffset("999ijklmno", "999", 15, 10); assertAbbreviateWithAbbrevMarkerAndOffset("_ghijklmno", "_", 16, 10); assertAbbreviateWithAbbrevMarkerAndOffset("+ghijklmno", "+", Integer.MAX_VALUE, 10); + // abbreviating a shorter string allows maxWidth < abbrevMarker.length * 2 + 1 + assertEquals("..de", StringUtils.abbreviate("abcde", "..", 4, 4)); + assertEquals("....fg", StringUtils.abbreviate("abcdefg", "....", 5, 6)); } // Fixed LANG-1463