I’ve stumbled upon that problem recently and couldn’t remember how to do it. Has you except it’s trivial to do and like most of what can be done in programming there more than one way to do it.
1- Good old jdk String 🙂
Since Java 1.5 you have the new String format method do something similar.
String.format(“%10s”, “bob”).replace(‘ ‘, ‘*’);
String.format(“%-10s”, “bassen”).replace(‘ ‘, ‘*’);
2- Apache StringUtils
Apache StringUtils has several methods to do this too: leftPad, rightPad, center and repeat.
if you use Apache StringUtils you get this :
StringUtils.leftPad(“bob”, 10, “*”)
StringUtils.rightPad(“bassen”, 10, “*”)
you get the same result
3- Google library Guava
If you still want to use another 3rd party library there Google utils library Guava that have something for you too:
Strings.padStart(“bob”, 10, ‘*’);//Equivalent of leftPad
Strings.padEnd(“bassen”, 10, ‘*’); //Equivalent of rightPad
Has you can see typically, to use these methods, you specify the String that you’d like to pad and the total size of the finished String. This total size includes the starting length of the String. You can specify an alternative padding character or characters via a third argument to these methods.