• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string format (with mask?)

 
Jan Groth
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi there,

i have a string, for example "127.0.0.1", which i need in this form: "127.000.000.001" (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,
jan
 
Tim McGuire
Ranch Hand
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

regards,
jan
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
127.000.000.001 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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

java.lang.String.format()
java.io.PrintStream.format()
java.io.PrintStream.printf()
java.io.PrintWriter.format()
java.io.PrintWriter.printf()

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 ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> 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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic