Organizational Research By

Surprising Reserch Topic

java – Right padding a String with Spaces and Zeros


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@
asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
64 views



Related Hot Questions



Government Jobs Opening


...