In this tutorial we are gonna see how to left pad a string with spaces and zeros:
1) Left pad with spaces
class LeftPaddingExample1 { public static void main(String[] args) { System.out.println("#" + padLeftSpaces("mystring", 10) + "@"); System.out.println("#" + padLeftSpaces("mystring", 15) + "@"); System.out.println("#" + padLeftSpaces("mystring", 20) + "@"); } public static String padLeftSpaces(String str, int n) { return String.format("%1$" + n + "s", str); } }
Output:
# mystring@ # mystring@ # mystring@
2) Left pad with Zeros
class LeftPaddingExample2 { public static void main(String[] args) { System.out.println("#" + padLeftZeros("mystring", 10) + "@"); System.out.println("#" + padLeftZeros("mystring", 15) + "@"); System.out.println("#" + padLeftZeros("mystring", 20) + "@"); } public static String padLeftZeros(String str, int n) { return String.format("%1$" + n + "s", str).replace(' ', '0'); } }
Output:
#00mystring@ #0000000mystring@ #000000000000mystring@
Leave a Reply