So I have been working on a naming convention which add 0's before a string. I'm trying to do this the short handed way before breaking everything into if statements. Here I print 0's before an int giving me an answer of 00005.
String test = null;
int n = 5;
test = String.format("%05d%n", n);
System.out.println(test);
Now what I would like to do is do this to a String. So for example if String n = "5"; it would give me an answer of 00005 and if String n = "20"; it would be 00020. I do not wish to use the integer method to change the string to and int, and back into a string. Any help would be appreciated. Thank you!
Assuming that
n
is aString
that represents a number, or more generally thatn
doesn't have any space characters:Not sure if it's the best way, but that's what I use.
Usage (assuming the static method is in a class called Utils) :
EDIT : generalized to any input String, character to pad with, and desired output length.
How about this?
This will only work if you have 5 or less digit numbers.
Ideone link to check code
Reference
To be honest, I also think 4 times how this code works, but after understanding I posted as this is something out of the box.