• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Padding a String

 
Steve Dyke
Ranch Hand
Posts: 1679
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I pad zeros to the right of a string to make it a specified length?
 
Jon Anslow
Greenhorn
Posts: 16
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1679
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have added to my class but get a cannot resolve error.
 
Jon Anslow
Greenhorn
Posts: 16
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12203
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuilder was added in 1.5 (if i recall correctly). what version of Java are you using?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic