Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


java – Left padding a String with Spaces and Zeros


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@

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
112 views



Related Hot Questions



Walkin Jobs Opening



Government Jobs Opening


...