Left padding a String with Zeros [duplicate]

2018-12-31 18:43发布

This question already has an answer here:

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.

20条回答
只靠听说
2楼-- · 2018-12-31 19:18

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.

查看更多
一个人的天荒地老
3楼-- · 2018-12-31 19:21

You may use apache commons StringUtils

StringUtils.leftPad("129018", 10, "0");

http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html

查看更多
何处买醉
4楼-- · 2018-12-31 19:21

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");

查看更多
倾城一夜雪
5楼-- · 2018-12-31 19:22

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"  
查看更多
余生无你
6楼-- · 2018-12-31 19:25

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

查看更多
伤终究还是伤i
7楼-- · 2018-12-31 19:26

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

查看更多
登录 后发表回答