beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

java – Right padding a String with Spaces and Zeros

By Chaitanya Singh | Filed Under: String Formatting

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:

#[email protected]
#[email protected]
#[email protected]

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap