Added support for ensureRight

This commit is contained in:
Shekhar Gulati
2016-05-17 18:50:27 +05:30
parent 7928d108c7
commit 169404c795
2 changed files with 27 additions and 0 deletions
+19
View File
@@ -370,6 +370,25 @@ public abstract class Strman {
return value.chars().mapToObj(ch -> leftPad(Integer.toString(ch), "0", 5)).collect(joining());
}
/**
* Ensures that the value ends with suffix. If it doesn't, it's appended.
*
* @param value The input String
* @param suffix The substr to be ensured to be right
* @param caseSensitive Use case (in-)sensitive matching for determining if value already ends with suffix
* @return
*/
public static String ensureRight(final String value, final String suffix, boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
boolean endsWith;
if (caseSensitive) {
endsWith = value.endsWith(suffix);
} else {
endsWith = value.toLowerCase().endsWith(suffix.toLowerCase());
}
return endsWith ? value : append(value, suffix);
}
public static String leftPad(final String value, final String pad, final int length) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (value.length() >= length) {
+8
View File
@@ -4,8 +4,11 @@ import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
import static org.junit.Assert.*;
import static strman.Strman.*;
@@ -298,6 +301,11 @@ public class StrmanTest {
assertThat(decEncode("A"), equalTo("00065"));
assertThat(decEncode("Á"), equalTo("00193"));
assertThat(decEncode("AA"), equalTo("0006500065"));
}
@Test
public void ensureRight_shouldEnsureStringEndsWithBar() throws Exception {
assertThat(Stream.of("foo", "foobar", "fooBAR").map(el -> ensureRight(el, "bar", false)).collect(toList()), hasItems("foobar", "foobar", "fooBAR"));
assertThat(Stream.of("foo", "foobar", "fooBAR").map(el -> ensureRight(el, "bar", true)).collect(toList()), hasItems("foobar", "foobar", "fooBARbar"));
}
}