What we want is to convert this:
abc
To this:
0000000abcSeven zeroes were padded to the left side of the String
The simplest way to solve this problem is to manually code the logic. Here is an example on how to perform the left padding using simple String concatenation:
public class Test { public static void main(String[] args) { String originalString = "abc"; String paddedString = originalString; while (paddedString.length() < 10) { paddedString = "0" + paddedString; } System.out.println(paddedString); } }
The character/String "0" is appended at the left side until the required number of characters is achieved.
The output is the expected String:
0000000abc
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(leftPadWithZeroes("abc", 10)); } public static String leftPadWithZeroes(String originalString, int length) { String paddedString = originalString; while (paddedString.length() < length) { paddedString = "0" + paddedString; } return paddedString; } }
We can use a StringBuilder or a StringBuffer to make the logic in the first example above more efficient. 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('0'); } sb.append(originalString); String paddedString = sb.toString(); System.out.println(paddedString); } }
Here is a modified version of the code that refactors the logic into a separate function. It achieves the same thing of left padding a String with zeroes given a target length.
public class Test { public static void main(String[] args) { System.out.println(leftPadWithZeroes("abc", 10)); } public static String leftPadWithZeroes(String originalString, int length) { StringBuilder sb = new StringBuilder(); while (sb.length() + originalString.length() < 10) { sb.append('0'); } sb.append(originalString); String paddedString = sb.toString(); return paddedString; } }
Here is a simple trick that uses substring to determine the String to pad. Here is a simple example:
public class Test { public static void main(String[] args) { String originalString = "abc"; String paddedString = "0000000000".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 zeroes before we perform a substring on it.
public class Test { public static void main(String[] args) { System.out.println(leftPadWithZeroes("abc", 10)); } public static String leftPadWithZeroes(String originalString, int length) { StringBuilder sb = new StringBuilder(); for (int i=0; i<length; i++) { sb.append("0"); } String padding = sb.toString(); String paddedString = padding.substring(originalString.length()) + originalString; return paddedString; } }