As you can see from the
Formatter documentation there is no way to pad a string with leading zeros. That comment is a little tongue in cheek: the documentation is a rather involved if you haven't seen the like before. But it is a good place to start and ask about if you are unsure.
There
are formatting commands that will right align a string to a given width padding the left hand end with spaces.
public class LeadingZeros {
public static void main(String[] args) {
String test = "some string";
String formatted = String.format("%20s", test);
System.out.println("-->" + formatted + "<--");
}
}
You could make a StringBuilder with the formatted string and then replace leading spaces with zero characters in a for loop.
-----
Your example, 10C --> 0000010C, looks suspiciously
not like any old string but, in fact, the hexidecimal form of an int value. In that case notice that the documentation talks about an x and an X conversion which perform a hexadecimal format of an int - in much the same way as d performs a
decimal format.
public class LeadingZeros {
public static void main(String[] args) {
//int test = 0x10C;
int test = 268; // same int
String formatted = String.format("%08X", test);
System.out.println("-->" + formatted + "<--");
}
}
(If 10C is intended to be a numerical value it is more appropriate to declare and use it an an int, not a String.)