0

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?

2 Answers 2

1

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] 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.