In this tutorial we are gonna see how to right pad a string with spaces and zeros:
1) Right pad with spaces
public class PadRightExample1 { public static void main(String[] argv) { System.out.println("#" + rightPadding("mystring", 10) + "@"); System.out.println("#" + rightPadding("mystring", 15) + "@"); System.out.println("#" + rightPadding("mystring", 20) + "@"); } public static String rightPadding(String str, int num) { return String.format("%1$-" + num + "s", str); } }
Output:
#mystring @ #mystring @ #mystring @
2) Right pad with zeros
public class PadRightExample2 { public static void main(String[] argv) { System.out.println("#" + rightPadZeros("mystring", 10) + "@"); System.out.println("#" + rightPadZeros("mystring", 15) + "@"); System.out.println("#" + rightPadZeros("mystring", 20) + "@"); } public static String rightPadZeros(String str, int num) { return String.format("%1$-" + num + "s", str).replace(' ', '0'); } }
Output:
#mystring00@ #mystring0000000@ #mystring000000000000@
Leave a Reply