Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

padding String with spaces -tried known methods but code not working!

807588Jan 31 2009 — edited Jan 31 2009
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 28 2009
Added on Jan 31 2009
3 comments
936 views