I am trying to figure out an easy way to pad a string with spaces at the end. The way that definitely works is a for loop where string = string + " "; until string is the length that I need. However, for several dozen strings this is a lot of unnecessary overhead. I've done some research and tried a few different things - yet none of them seem to actually pad the string.
import org.apache.commons.lang.StringUtils;
public class Test
{
public static void main(String[] args)
{
String one = "1234";
//print string at current lenght
System.out.println(one+"*");
//try padding using String.format (in padRight method below)
one = padRight(one,(8-one.length()));
System.out.println(one+"*");
one="1234";
//try padding using StringUtils
String tmp = StringUtils.rightPad(one, (8-one.length()));
System.out.println(tmp+"*");
}
private static String padRight(String s, int n)
{
return String.format("%1$-" + n + "s", s);
}
}
I've researched and these are the two most common methods people are suggesting. I am using java 1.5 so the String.format should work.. however, when I run it (I use JBuilder) the output is always "1234*".... after I try to pad it the output should be "1234 *" (with 4 spaces between the 4 and *) . Any suggestions is greatly appreciated! Thanks in advance.