Pad string. (#5669)

This commit is contained in:
cdjole 2018-11-12 04:44:35 +01:00 committed by maibin
parent b35ad9381d
commit c0a5e01918
2 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,34 @@
package com.baeldung.string.padding;
public class StringPaddingUtil {
public static String padLeftSpaces(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < length - inputString.length()) {
sb.append(' ');
}
sb.append(inputString);
return sb.toString();
}
public static String padLeft(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(' ');
}
return sb.substring(inputString.length()) + inputString;
}
public static String padLeftZeros(String inputString, int length) {
return String
.format("%1$" + length + "s", inputString)
.replace(' ', '0');
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.string.padding;
import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringPaddingUtilUnitTest {
String inputString = "123456";
String expectedPaddedStringSpaces = " 123456";
String expectedPaddedStringZeros = "0000123456";
int minPaddedStringLength = 10;
@Test
public void givenString_whenPaddingWithSpaces_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringSpaces, StringPaddingUtil.padLeftSpaces(inputString, minPaddedStringLength));
}
@Test
public void givenString_whenPaddingWithSpacesUsingSubstring_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringSpaces, StringPaddingUtil.padLeft(inputString, minPaddedStringLength));
}
@Test
public void givenString_whenPaddingWithZeros_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringZeros, StringPaddingUtil.padLeftZeros(inputString, minPaddedStringLength));
}
@Test
public void givenString_whenPaddingWithSpacesUsingStringUtils_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringSpaces, StringUtils.leftPad(inputString, minPaddedStringLength));
}
@Test
public void givenString_whenPaddingWithZerosUsingStringUtils_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringZeros, StringUtils.leftPad(inputString, minPaddedStringLength, "0"));
}
@Test
public void givenString_whenPaddingWithSpacesUsingGuavaStrings_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringSpaces, Strings.padStart(inputString, minPaddedStringLength, ' '));
}
@Test
public void givenString_whenPaddingWithZerosUsingGuavaStrings_thenStringPaddedMatches() {
assertEquals(expectedPaddedStringZeros, Strings.padStart(inputString, minPaddedStringLength, '0'));
}
}