Fixed #13. Added support for leftPad function

This commit is contained in:
Shekhar Gulati
2016-05-20 20:07:08 +05:30
parent 08945f3d04
commit de2e7af797
2 changed files with 20 additions and 1 deletions
+10 -1
View File
@@ -530,9 +530,18 @@ public abstract class Strman {
return value.substring(value.length() - n);
}
/**
* Returns a new string of a given length such that the beginning of the string is padded.
*
* @param value The input String
* @param pad The pad
* @param length Length of the String we want
* @return Padded String
*/
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) {
validate(pad, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (value.length() > length) {
return value;
}
return append(Stream.generate(() -> pad).limit(length - value.length()).collect(joining()), value);
+10
View File
@@ -430,4 +430,14 @@ public class StrmanTest {
assertThat(last("", 3), equalTo(""));
assertThat(last("f", 3), equalTo("f"));
}
@Test
public void leftPad_shouldAddPaddingOnTheLeft() throws Exception {
assertThat(leftPad("1", "0", 5), equalTo("00001"));
assertThat(leftPad("01", "0", 5), equalTo("00001"));
assertThat(leftPad("001", "0", 5), equalTo("00001"));
assertThat(leftPad("0001", "0", 5), equalTo("00001"));
assertThat(leftPad("00001", "0", 5), equalTo("00001"));
}
}