使用Java String格式生成可变大小的数字而不带前导零

时间:2014-08-07 07:21:55

标签: java string format string-formatting

如果您尝试此代码:

public class StringFormat {

    public void printIt() {

        String pattern = "%%s%%0%dd%%s"; // <-- THIS SHOULD BE FIXED

        String arrayName = "aaaa[12]";
        int arrayLength = 12;
        String printfString = String.format(pattern,
                Integer.toString(arrayLength - 1).length());        
        int arrayAt = 4;
        int arrayTill = 7;

        for (int arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
            String formattedString = 
                String.format(printfString, arrayName.substring(0, arrayAt + 1),
                         arrayIndex, arrayName.substring(arrayTill));

            System.out.println(formattedString.toString());
        }
    }

    public static void main(String[] args)
    {
        StringFormat stringFormat = new StringFormat();
        stringFormat.printIt();
    }   
}

你会看到输出是:

aaaa[00]
aaaa[01]
.......
aaaa[09]
aaaa[10]
aaaa[11]

我不希望在数组大小中有前导零。 输出应为:

aaaa[0]
aaaa[1]
.......
aaaa[9]
aaaa[10]
aaaa[11]

可以更改模式字符串%%s%%0%dd%%s来执行此操作,还是应该使用两种模式分支执行 - 对于单数字和双数字?

2 个答案:

答案 0 :(得分:1)

如果我改变了这个

String pattern = "%%s%%0%dd%%s"; // <-- THIS SHOULD BE FIXED

到这个

String pattern = "%%s%%d%%s";

我得到了输出

aaaa[0]
aaaa[1]
aaaa[2]
aaaa[3]
aaaa[4]
aaaa[5]
aaaa[6]
aaaa[7]
aaaa[8]
aaaa[9]
aaaa[10]
aaaa[11]

答案 1 :(得分:1)

您可以更改格式

    String pattern = "%%s%%d%%s"; // <-- New format

    String arrayName = "aaaa[12]";
    int arrayLength = 12;
    String printfString = String.format(pattern,
            Integer.toString(arrayLength - 1).length());
    int arrayAt = 4;
    int arrayTill = 7;

    for (int arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
        String formattedString =
                String.format(printfString, arrayName.substring(0, arrayAt + 1),
                        arrayIndex, arrayName.substring(arrayTill));

        System.out.println(formattedString); // no need toString()
    }

你不需要

  System.out.println(formattedString.toString()); // system.out.print() will call
                                                  // toString()