如何格式化带有前导零的Java字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4051887/
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 11:00:33  来源:igfitidea点击:

How to format a Java string with leading zero?

javastringformattingformat

提问by Roy

Here is the String, for example:

这是字符串,例如:

"Apple"

and I would like to add zero to fill in 8 chars:

我想添加零来填充 8 个字符:

"000Apple"

How can I do so?

我怎么能这样做?

采纳答案by Chris Lercher

In case you have to do it without the help of a library:

如果您必须在没有图书馆帮助的情况下执行此操作:

("00000000" + "Apple").substring("Apple".length())

(Works, as long as your String isn't longer than 8 chars.)

(有效,只要您的字符串不超过 8 个字符。)

回答by Bozho

 StringUtils.leftPad(yourString, 8, '0');

This is from commons-lang. See javadoc

这是来自commons-lang见javadoc

回答by Alex Rashkov

public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}

回答by kaliatech

Use Apache Commons StringUtils.leftPad(or look at the code to make your own function).

使用Apache Commons StringUtils.leftPad(或查看代码制作自己的函数)。

回答by mR_fr0g

It isn't pretty, but it works. If you have access apache commons i would suggest that use that

它不漂亮,但它有效。如果您可以访问 apache commons,我建议您使用它

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}

回答by Arne Deutsch

public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}

回答by bragboy

You may have to take care of edgecase. This is a generic method.

您可能需要处理边缘情况。这是一个通用的方法。

public class Test {
    public static void main(String[] args){
        System.out.println(padCharacter("0",8,"hello"));
    }
    public static String padCharacter(String c, int num, String str){
        for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
        return str;
    }
}

回答by robert_x44

String input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();

回答by Fathah Rehman P

public static void main(String[] args)
{
    String stringForTest = "Apple";
    int requiredLengthAfterPadding = 8;
    int inputStringLengh = stringForTest.length();
    int diff = requiredLengthAfterPadding - inputStringLengh;
    if (inputStringLengh < requiredLengthAfterPadding)
    {
        stringForTest = new String(new char[diff]).replace("
String.format("%0"+length+"d",0)
", "0")+ stringForTest; } System.out.println(stringForTest); }

回答by ChadyWady

You can use the String.format method as used in another answer to generate a string of 0's,

您可以使用另一个答案中使用的 String.format 方法来生成一个 0 的字符串,

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

This can be applied to your problem by dynamically adjusting the number of leading 0's in a format string:

这可以通过动态调整格式字符串中前导 0 的数量来解决您的问题:

##代码##

It's still a messy solution, but has the advantage that you can specify the total length of the resulting string using an integer argument.

它仍然是一个凌乱的解决方案,但优点是您可以使用整数参数指定结果字符串的总长度。