Print 000 infront of String, I can get INT to work but not string
Hi All,
I have look thru internet on how to print the 0000 in front of string but i could not find it. I can print out integer without any problem. The code i using for int number is:-
int x = 101
String.format("%1$08d", x));
Output:
00000101
But if i want to print something like C or 10C to be 0000000C and 0000010C i cannot use the above function.
Anyone can help with this?
Re: Print 000 infront of String, I can get INT to work but not string
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.
Code :
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.
Code :
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.)