Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用0'填充字符串;他正在使用格式化程序_Java_Formatter - Fatal编程技术网

Java 用0'填充字符串;他正在使用格式化程序

Java 用0'填充字符串;他正在使用格式化程序,java,formatter,Java,Formatter,我知道我可以使用以下方法填充空格: String.format("%6s", "abc"); // ___abc ( three spaces before abc 但我似乎找不到如何制作: 000abc 编辑: 在询问此问题之前,我尝试了%06s。只是在更多(未尝试过的)答案出现之前让你知道 目前我有:String.format(“%6s”,data.).replace(“'0'),但我认为一定有更好的方法。 P>您应该考虑从Apache Con Son中使用这样的字符串操作任务,因为代

我知道我可以使用以下方法填充空格:

String.format("%6s", "abc"); // ___abc ( three spaces before abc
但我似乎找不到如何制作:

000abc
编辑:

在询问此问题之前,我尝试了
%06s
。只是在更多(未尝试过的)答案出现之前让你知道

目前我有:
String.format(“%6s”,data.).replace(“'0')
,但我认为一定有更好的方法。


<> P>您应该考虑从Apache Con Son中使用这样的字符串操作任务,因为代码会变得更可读。您的示例是
StringUtils.leftPad(“abc”,6,”)

快速且脏(将“000…00”字符串的长度设置为您支持的最大长度):

public静态字符串leftpaddwithzero(字符串x,int minlen){

返回x.length()尝试滚动您自己的静态实用程序方法

public static String leftPadStringWithChar(String s, int fixedLength, char c){

    if(fixedLength < s.length()){
        throw new IllegalArgumentException();
    }

    StringBuilder sb = new StringBuilder(s);

    for(int i = 0; i < fixedLength - s.length(); i++){
        sb.insert(0, c);
    }

    return sb.toString();
}
输出

000abc

无论如何,为这类东西找一个你喜欢的库,并了解你闪亮的新工具箱中有什么,这样你就可以重新发明更少的轮子(有时是扁平的)。我更喜欢Apache Commons。在这种情况下,它们是等价的:

Strings.padStart("abc",6,'0');

顺便说一句,在问这个问题之前,我用了
%06s
,只是在更多(未尝试的)答案出现之前让你知道。这个怎么样?
System.out.println(leftPadStringWithChar("abc", 6, '0'));
000abc
Strings.padStart("abc",6,'0');