Add left Pad to String - Java java.lang

Java examples for java.lang:String Pad

Description

Add left Pad to String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        int size = 2;
        String pad = "java2s.com";
        System.out.println(leftPad(str, size, pad));
    }//from   w ww  .ja va 2  s.  co m

    public static String leftPad(String str, int size, String pad) {
        StringBuilder builder = new StringBuilder();
        addPad(str, size, pad, builder);
        builder.append(str);
        return builder.substring(0, size);
    }

    public static void addPad(String str, int size, String pad,
            StringBuilder builder) {
        for (int i = 0; i < size - str.length(); i++) {
            builder.append(pad);
        }
    }
}

Related Tutorials