*
The moose likes Beginning Java and the fly likes Padding a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Padding a String" Watch "Padding a String" New topic
Author

Padding a String

Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1393
How do I pad zeros to the right of a string to make it a specified length?
Jon Anslow
Greenhorn

Joined: May 05, 2006
Posts: 16

Hi Steve,

The StringBuilder Class may assist you in adding zeros to the String you wish to pad out:



You may want to put the append() method call in a loop, to keep on appending zeros to the StringBuilder object until you reach your desired padded length. Once complete, calling the paddedString.toString() method will give you a padded String object.

Regards,
Jon
[ July 16, 2007: Message edited by: Jon Anslow ]
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1393
I have added to my class but get a cannot resolve error.
Jon Anslow
Greenhorn

Joined: May 05, 2006
Posts: 16

Apoligies, Steve. I forgot to mention that the StringBuilder Class is part of Java 5. If you are using an earlier version, the StringBuffer Class could be used.

Regards,
Jon
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

StringBuilder was added in 1.5 (if i recall correctly). what version of Java are you using?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
If you're going to do a lot of this you might want to make (or find) a String utility library. You could reuse a method like this over and over:

Note this lets you pad with anything, even two or more characters, not just 0. And it truncates strings that are longer than the desired length.

I made a set of methods like this my first week of Java just for something to do. It might be smarter to look around and find a tested library and save th writing time. Or it might be fun to make.

If you write your own, try String, StringBuilder (if you can), StringBuffer and see which feels best.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Padding a String
 
Similar Threads
WA #1.....word association
ResultSet to Array
date format with MS Access database
Tech Word Game
How to convert byte array into string array?