What we want is to convert this:
abcTo this:
abcTo have a length of 10, 7 spaces was padded to the left side of the given String.
We can manually code a solution for this problem. We can simply loop and continuosly concatenate a space to the left of the String until the desired length is achieved. Here is an example:
public class Test { public static void main(String[] args) { String originalString = "abc"; String paddedString = originalString; while (paddedString.length() < 10) { paddedString = " " + paddedString; } System.out.println(paddedString); } }
Spaces are appended at the left side using a while loop.
The output is the expected String:
abc
Here is a modified version of the code that refactors the logic into a separate function:
public class Test { public static void main(String[] args) { System.out.println(leftPadWithSpaces("abc", 10)); } public static String leftPadWithSpaces(String originalString, int length) { String paddedString = originalString; while (paddedString.length() < length) { paddedString = " " + paddedString; } return paddedString; } }
We can reuse the logic above by using a StringBuilder to make it run more efficiently. Here is an example:
public class Test { public static void main(String[] args) { String originalString = "abc"; StringBuilder sb = new StringBuilder(); while (sb.length() + originalString.length() < 10) { sb.append(' '); } sb.append(originalString); String paddedString = sb.toString(); System.out.println(paddedString); } }
Here is a refactored solution that separates the logic into a function. It does the same thing by padding spaces to achieve the target String length.
public class Test { public static void main(String[] args) { System.out.println(leftPadWithSpaces("abc", 10)); } public static String leftPadWithSpaces(String originalString, int length) { StringBuilder sb = new StringBuilder(); while (sb.length() + originalString.length() < 10) { sb.append(' '); } sb.append(originalString); String paddedString = sb.toString(); return paddedString; } }
Here is a simple trick that uses substring to determine the String to pad. We start with a String with 10 spaces and perform a substring on it. Here is a simple example:
public class Test { public static void main(String[] args) { String originalString = "abc"; String paddedString = " ".substring(originalString.length()) + originalString; System.out.println(paddedString); } }Here is a modified version of the code that refactors the logic into a separate function. We first build a series of spaces before we perform a substring on it.
public class Test { public static void main(String[] args) { System.out.println(leftPadWithSpaces("abc", 10)); } public static String leftPadWithSpaces(String originalString, int length) { StringBuilder sb = new StringBuilder(); for (int i=0; i<length; i++) { sb.append(" "); } String padding = sb.toString(); String paddedString = padding.substring(originalString.length()) + originalString; return paddedString; } }