Java 用零左填充字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4469717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:52:17  来源:igfitidea点击:

Left padding a String with Zeros

javastringpadding

提问by jai

I've seen similar questions hereand here.

我在这里这里看到过类似的问题。

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

但是我不知道如何用零填充字符串。

input: "129018" output: "0000129018"

输入:“129018” 输出:“0000129018”

The total output length should be TEN.

总输出长度应为十。

采纳答案by khachik

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.

如果没有,我想知道怎么做

回答by thejh

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

回答by Oliver Michels

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

the second parameter is the desired output length

第二个参数是所需的输出长度

"0" is the padding char

“0”是填充字符

回答by Satish

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

回答by user85421

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();
    }

回答by Rick Hanlon II

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

这将填充任何字符串的总宽度为 10,而无需担心解析错误:

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:

你可以用你想要填充的任何字符替换“#”字符,重复你想要的字符串总宽度的次数。例如,如果您想在左侧添加零以使整个字符串为 15 个字符长:

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.

与 khachik 的答案相比,这样做的好处是它不使用 Integer.parseInt,它会抛出异常(例如,如果您要填充的数字太大,如 12147483647)。缺点是,如果您要填充的内容已经是 int,那么您必须将其转换为 String 并返回,这是不可取的。

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

所以,如果你确定它是一个 int,khachik 的答案就很好用。如果没有,那么这是一个可能的策略。

回答by bockymurphy

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

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());
    }
}

回答by nullpotent

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)

回答by Nagarajan S R

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

输出:字符串: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

使用链接下载jar http://commons.apache.org/proper/commons-lang/download_lang.cgi