diff --git a/src/main/java/strman/Strman.java b/src/main/java/strman/Strman.java index 5eab8aa..bc4519d 100644 --- a/src/main/java/strman/Strman.java +++ b/src/main/java/strman/Strman.java @@ -467,6 +467,7 @@ public abstract class Strman { /** * Tests if two Strings are inequal + * * @param first The first String * @param second The second String * @return true if first and second are not equal false otherwise @@ -475,6 +476,22 @@ public abstract class Strman { return !Objects.equals(first, second); } + /** + * Inserts 'substr' into the 'value' at the 'index' provided. + * + * @param value The input String + * @param substr The String to insert + * @param index The index to insert substr + * @return String with substr added + */ + public static String insert(final String value, final String substr, final int index) { + validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); + validate(substr, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); + if (index > value.length()) { + return value; + } + return value.substring(0, index) + substr + value.substring(index); + } public static String leftPad(final String value, final String pad, final int length) { validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); diff --git a/src/test/java/strman/StrmanTest.java b/src/test/java/strman/StrmanTest.java index da5b8c2..3bf2089 100644 --- a/src/test/java/strman/StrmanTest.java +++ b/src/test/java/strman/StrmanTest.java @@ -387,4 +387,13 @@ public class StrmanTest { assertThat(inequal("a", "a"), equalTo(false)); assertThat(inequal("0", "1"), equalTo(true)); } + + @Test + public void insert_shouldInsertStringAtIndex() throws Exception { + assertThat(insert("fbar", "oo", 1), equalTo("foobar")); + assertThat(insert("foo", "bar", 3), equalTo("foobar")); + assertThat(insert("foobar", "x", 5), equalTo("foobaxr")); + assertThat(insert("foobar", "x", 6), equalTo("foobarx")); + assertThat(insert("foo bar", "asadasd", 100), equalTo("foo bar")); + } } \ No newline at end of file