It's not a secret anymore!
The moose likes Java in General and the fly likes string format (with mask?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "string format (with mask?)" Watch "string format (with mask?)" New topic

string format (with mask?)

Jan Groth
Ranch Hand

Joined: Feb 03, 2004
Posts: 456
hi there,

i have a string, for example "", which i need in this form: "" (filled up with zero).

right now i'm working with a loop and a set of conditions, but i'm sure there is a more elegant (=efficent) way. i played with MaskFormatter("###.###.###.###"), but I'm not sure if this solves my problems. Even if i need this conversion for a text field, I don't want to be too close to Swing, I'd like to solve this problem in a more general way...

many thanks for hints,
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

I would Split the string by "." and left-pad with the "0" character

see String.split()

Here is a nice padding routine
Jan Groth
Ranch Hand

Joined: Feb 03, 2004
Posts: 456
hi tim,

that's exactly what i'm doing and what i described with "the loop". takes almost 10 lines of code - and hey, there must be are better way to format a number, or not?

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791 isn't a number in any system I know. That's about as good as you're going to do for formatting a rather complex string. As an exercise see if you can make your pad routine about half as long as the one linked above. That part is reusable as a bonus.

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
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
If you're using JDK 5, then yes there is another (better?) way - using a java.util.Formatter. This is a little hard to figure out how to use at first, but it's well worth the effort, I think, as it's very powerful and flexible.

Note that you usually don't need to create a Formatter directly. There are a number of convenience methods built into preexisting classes:


For example to pad a number with zeros to 3 digits, you can use:

String output = String.format("%03d", Integer.parseInt(input));
[ September 09, 2005: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> takes almost 10 lines of code

if you want a 1-liner, this works for the example given, but I don't know
if it is 'bullet-proof' - I'd prefer split(), easier to read/modify

I agree. Here's the link:
subject: string format (with mask?)
jQuery in Action, 3rd edition