katericata
katericata

Reputation: 1058

Produce variable size digits without leading zeros with Java String format

If you try this code:

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

you will see that the output is:

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

I do not want to have leading zeros in the array size. The output should be:

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

Can the pattern string %%s%%0%dd%%s be changed to do that or shall I branch the execution with two patterns - for single and double digits?

Upvotes: 0

Views: 168

Answers (2)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can change your format as this

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

You don't need

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

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

If I change this

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

to this

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

I get the output

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

Upvotes: 1

Related Questions