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
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

java – Left padding a String with Spaces and Zeros

By Chaitanya Singh | Filed Under: String Formatting

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:

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

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:

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

Enjoyed this post? Try these related posts

  1. How to remove only trailing spaces of a string in Java
  2. java – Right padding a String with Spaces and Zeros

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 – 2021 BeginnersBook . Privacy Policy . Sitemap