Left padding a String with Zeros

JavaStringPadding

Java Problem Overview


I've seen similar questions here and here.

But am not getting how to left pad a String with Zero.

input: "129018" output: "0000129018"

The total output length should be TEN.

Java Solutions


Solution 1 - Java

If your string contains numbers only, you can make it an integer and then do padding:

String.format("%010d", Integer.parseInt(mystring));

If not I would like to know how it can be done.

Solution 2 - Java

String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")

the second parameter is the desired output length

"0" is the padding char

Solution 3 - Java

This will pad left any string to a total width of 10 without worrying about parse errors:

String unpadded = "12345"; 
String padded = "##########".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "#####12345"

If you want to pad right:

String unpadded = "12345"; 
String padded = unpadded + "##########".substring(unpadded.length());

//unpadded is "12345"
//padded   is "12345#####"  

You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. E.g. if you want to add zeros to the left so that the whole string is 15 characters long:

String unpadded = "12345"; 
String padded = "000000000000000".substring(unpadded.length()) + unpadded;
    
//unpadded is "12345"
//padded   is "000000000012345"  

The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.

So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.

Solution 4 - Java

String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);

Solution 5 - Java

String str = "129018";
StringBuilder sb = new StringBuilder();

for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
    sb.append('0');
}

sb.append(str);
String result = sb.toString();

Solution 6 - Java

Solution 7 - Java

To format String use

import org.apache.commons.lang.StringUtils;

public class test {

	public static void main(String[] args) {

		String result = StringUtils.leftPad("wrwer", 10, "0");
		System.out.println("The String : " + result);

	}
}

Output : The String : 00000wrwer

Where the first argument is the string to be formatted, Second argument is the length of the desired output length and third argument is the char with which the string is to be padded.

Use the link to download the jar http://commons.apache.org/proper/commons-lang/download_lang.cgi

Solution 8 - Java

If you need performance and know the maximum size of the string use this:

String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;

Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a java.lang.StringIndexOutOfBoundsException.

Solution 9 - Java

An old question, but I also have two methods.


For a fixed (predefined) length:

    public static String fill(String text) {
        if (text.length() >= 10)
            return text;
        else
            return "0000000000".substring(text.length()) + text;
    }

For a variable length:

    public static String fill(String text, int size) {
        StringBuilder builder = new StringBuilder(text);
        while (builder.length() < size) {
            builder.append('0');
        }
        return builder.toString();
    }

Solution 10 - Java

Use Google Guava:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

Strings.padStart("129018", 10, '0') returns "0000129018"  

Solution 11 - Java

I prefer this code:

public final class StrMgr {

	public static String rightPad(String input, int length, String fill){		 			
		String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
		return pad.substring(0, length);			  
	}		

	public static String leftPad(String input, int length, String fill){		 	
		String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
		return pad.substring(pad.length() - length, pad.length());
	}
}

and then:

System.out.println(StrMgr.leftPad("hello", 20, "x")); 
System.out.println(StrMgr.rightPad("hello", 20, "x"));

Solution 12 - Java

Based on @Haroldo Macêdo's answer, I created a method in my custom Utils class such as

/**
 * Left padding a string with the given character
 *
 * @param str     The string to be padded
 * @param length  The total fix length of the string
 * @param padChar The pad character
 * @return The padded string
 */
public static String padLeft(String str, int length, String padChar) {
    String pad = "";
    for (int i = 0; i < length; i++) {
        pad += padChar;
    }
    return pad.substring(str.length()) + str;
}

Then call Utils.padLeft(str, 10, "0");

Solution 13 - Java

Here's another approach:

int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)

Solution 14 - Java

Here's my solution:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

Output: 00000101

Solution 15 - Java

Right padding with fix length-10: String.format("%1$-10s", "abc") Left padding with fix length-10: String.format("%1$10s", "abc")

Solution 16 - Java

Here is a solution based on String.format that will work for strings and is suitable for variable length.

public static String PadLeft(String stringToPad, int padToLength){
    String retValue = null;
    if(stringToPad.length() < padToLength) {
        retValue = String.format("%0" + String.valueOf(padToLength - stringToPad.length()) + "d%s",0,stringToPad);
    }
    else{
        retValue = stringToPad;
    }
    return retValue;
}

public static void main(String[] args) {
	System.out.println("'" + PadLeft("test", 10) + "'");
	System.out.println("'" + PadLeft("test", 3) + "'");
	System.out.println("'" + PadLeft("test", 4) + "'");
	System.out.println("'" + PadLeft("test", 5) + "'");
}

Output: '000000test' 'test' 'test' '0test'

Solution 17 - Java

The solution by Satish is very good among the expected answers. I wanted to make it more general by adding variable n to format string instead of 10 chars.

int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);

This will work in most situations

Solution 18 - Java

    int number = -1;
    int holdingDigits = 7;
    System.out.println(String.format("%0"+ holdingDigits +"d", number));

Just asked this in an interview........

My answer below but this (mentioned above) is much nicer->

String.format("%05d", num);

My answer is:

static String leadingZeros(int num, int digitSize) {
    //test for capacity being too small.
    
    if (digitSize < String.valueOf(num).length()) {
        return "Error : you number  " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";

        //test for capacity will exactly hold the number.
    } else if (digitSize == String.valueOf(num).length()) {
        return String.valueOf(num);

        //else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError 

        //else calculate and return string
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digitSize; i++) {
            sb.append("0");
        }
        sb.append(String.valueOf(num));
        return sb.substring(sb.length() - digitSize, sb.length());
    }
}

Solution 19 - Java

Check my code that will work for integer and String.

Assume our first number is 129018. And we want to add zeros to that so the the length of final string will be 10. For that you can use following code

    int number=129018;
    int requiredLengthAfterPadding=10;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

Solution 20 - Java

I have used this:

DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));

Result: 00123

I hope you find it useful!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjaiView Question on Stackoverflow
Solution 1 - JavakhachikView Answer on Stackoverflow
Solution 2 - JavaOliver MichelsView Answer on Stackoverflow
Solution 3 - JavaRick Hanlon IIView Answer on Stackoverflow
Solution 4 - JavaSatishView Answer on Stackoverflow
Solution 5 - JavathejhView Answer on Stackoverflow
Solution 6 - JavathkView Answer on Stackoverflow
Solution 7 - JavaNagarajan S RView Answer on Stackoverflow
Solution 8 - JavaHaroldo MacedoView Answer on Stackoverflow
Solution 9 - Javauser85421View Answer on Stackoverflow
Solution 10 - JavaThoView Answer on Stackoverflow
Solution 11 - JavastroberingView Answer on Stackoverflow
Solution 12 - JavaSithuView Answer on Stackoverflow
Solution 13 - JavanullpotentView Answer on Stackoverflow
Solution 14 - Javash3r1View Answer on Stackoverflow
Solution 15 - JavaArunView Answer on Stackoverflow
Solution 16 - JavaP.V.M. KesselsView Answer on Stackoverflow
Solution 17 - JavaPrabhuView Answer on Stackoverflow
Solution 18 - JavabockymurphyView Answer on Stackoverflow
Solution 19 - JavaFathah Rehman PView Answer on Stackoverflow
Solution 20 - JavaCarlos MuñozView Answer on Stackoverflow