Just the opposite of padding a string on the left with zeros or spaces, this example will show how to pad a string with trailing spaces and zeros using java, guava and apache commons. If you are working in an IBM COBOL shop there is a lot of instance where you need to fill a message area with exactly the number of characters specified. So if piece of code is expecting 25 total characters, you only have 10, you will have to fill in the remaining characters with spaces or another value.
Straight up Java
This snippet will use a formatter to pad a string with trailing zeros. We will define a pattern with a width of 10 and provide 'levelup' as the object to inject to the String.format method. Then calling the String.replace method we will replace all spaces with a zero.
This snippet will right pad a string with spaces using String.format. We will define a pattern with a width of 10 and pass in 'levelup'. The remainder length will be padded with spaces.
This snippet will right pad a string with zeros using guava's Strings utility class. Using Strings.padEnd we will pass in the String to prepend to, a total length of the string when it is done and the value it should add to the end.
This snippet will right pad a string with spaces using guava's Strings utility. Like above, we will use Strings.padEnd passing in three variables. First the string to format with spaces, second the minimum length and third the character in this case a space.
This code snippet will left justify a string while padding it with zeros using apache commons StringUtils.rightPad. In other words, it will right pad a String with a specified String and size.
This snippet will use a pad function to pad spaces at the end of a string with a specified length using apache commons StringUtils.rightPad.