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?