| Author |
Padding a String
|
Steve Dyke
Ranch Hand
Joined: Nov 16, 2004
Posts: 1254
|
|
|
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: 1254
|
|
|
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: 9939
|
|
|
StringBuilder was added in 1.5 (if i recall correctly). what version of Java are you using?
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
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
|
 |
 |
|
|
subject: Padding a String
|
|
|