Java PadLeft/PadRight

Java left pad/right pad string functions. These’re also equivalent to C# and VB.Net PadLeft and PadRight methods.

package test;

public class Pad {
    public static String lpad(String str, int n, CharSequence c) {
        return (new String(new char[n-str.length()])).replace("\0", c) + str;
    }

    public static String rpad(String str, int n, CharSequence c) {
        return str + (new String(new char[n-str.length()])).replace("\0", c);
    }
    
    public static void main(String[] args) {
        System.out.println(lpad("astring", 10, "0"));
        System.out.println(rpad("astring", 10, "0"));
    }
}

Output:

000astring
astring000

Leave a Reply