From 8d2a0291915aeabd53d0d486ecbdc2641af04aa5 Mon Sep 17 00:00:00 2001 From: Claude Warren Date: Sun, 13 Oct 2024 11:43:29 +0100 Subject: [PATCH] addition of filledString() method --- .../org/apache/commons/lang3/StringUtils.java | 16 ++++++++++++++++ .../apache/commons/lang3/StringUtilsTest.java | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index b9403c79347..7724383643a 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -1852,6 +1852,22 @@ public static boolean equalsIgnoreCase(final CharSequence cs1, final CharSequenc return Strings.CI.equals(cs1, cs2); } + /** + * Constructs a string of specified length filled with the specified char. + * @param length the length of the final string. + * @param fillChar the character to file it will. + * @return A string of specified length filled with the specified char. + * @since 1.10.0 + */ + public static String filledString(final int length, final char fillChar) { + if (length < 0) { + throw new IllegalArgumentException("Length must not be negative"); + } + final char[] padding = new char[length]; + Arrays.fill(padding, fillChar); + return new String(padding); + } + /** * Returns the first value in the array which is not empty (""), * {@code null} or whitespace only. diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index e1102f74e64..e8ef4899892 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -809,6 +809,13 @@ public void testEscapeSurrogatePairsLang858() { assertEquals("\\uDBFF\\uDFFD", StringEscapeUtils.escapeEcmaScript("\uDBFF\uDFFD")); //fail LANG-858 } + @Test + public void testFilledString() { + assertEquals("-----", StringUtils.filledString(5, '-')); + assertEquals("", StringUtils.filledString(0, '-')); + assertThrows(IllegalArgumentException.class, () -> StringUtils.filledString(-1, '-')); + } + @Test public void testGeorgianSample() { final char[] arrayI = {