Added support for ensureLeft and its variants

This commit is contained in:
Shekhar Gulati
2016-05-09 15:32:37 +05:30
parent 217ebf9361
commit 47e20b35eb
2 changed files with 45 additions and 0 deletions
+28
View File
@@ -265,6 +265,34 @@ public abstract class Strman {
return value.toLowerCase().indexOf(search.toLowerCase(), remainingLength) > -1;
}
/**
* Ensures that the value begins with prefix. If it doesn't exist, it's prepended. It is case sensitive.
*
* @param value input
* @param prefix prefix
* @return string with prefix if it was not present.
*/
public static String ensureLeft(final String value, final String prefix) {
return ensureLeft(value, prefix, true);
}
/**
* Ensures that the value begins with prefix. If it doesn't exist, it's prepended.
*
* @param value input
* @param prefix prefix
* @param caseSensitive true or false
* @return string with prefix if it was not present.
*/
public static String ensureLeft(final String value, final String prefix, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.startsWith(prefix) ? value : prefix + value;
}
String _value = value.toLowerCase();
String _prefix = prefix.toLowerCase();
return _value.startsWith(_prefix) ? value : prefix + value;
}
private static long countSubstr(String value, String subStr, boolean allowOverlapping, long count) {
int position = value.indexOf(subStr);
+17
View File
@@ -230,4 +230,21 @@ public class StrmanTest {
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "BAR", el.length() - 1, false)));
}
@Test
public void ensureLeft_shouldEnsureValueStartsWithFoo() throws Exception {
String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(ensureLeft(el, "foo"), equalTo("foobar")));
}
@Test
public void ensureLeft_notCaseSensitive_shouldEnsureValueStartsWithFoo() throws Exception {
assertThat(ensureLeft("foobar", "FOO", false), equalTo("foobar"));
assertThat(ensureLeft("bar", "FOO", false), equalTo("FOObar"));
}
}