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
Not sure if it's the best way, but that's what I use.
public static String pad (String input, char with, int desiredLength)
{
if (input.length() >= desiredLength) {
return input;
}
StringBuilder output = new StringBuilder (desiredLength);
for (int i = input.length (); i < desiredLength; i++) {
output.append (with);
}
output.append (input);
return output.toString();
}
Usage (assuming the static method is in a class called Utils) :
System.out.println (Utils.pad(myString,'0',10));
EDIT : generalized to any input String, character to pad with, and desired output length.