SlinkyMation SlinkyMation - 1 year ago 67
Java Question

Constructing a string that does not include integer if it is 0 in Java?

Let's say that I have:

int hours = 0;
int minutes = 0;
int seconds = 5;
System.out.println("Simplified time: " + hours + ":" + minutes + ":" + seconds + ":");

it will obviously print out:

Simplified time: 0:0:5:

Does anyone have any idea to make it print out like:

Simplified time: 5:

without using some if else statements? Of course if (hours>0) I would like it to print out the whole Print statement Like if (hours=3) I want it to print out:

Simplified time: 3:0:5:

Answer Source

It looks like you are trying to remove leading zeroes and : after them.

If that is the case you can apply replaceAll(regex,replacement) to x:x:x: part to remove 1 or 2 of 0: placed at start (we don't want to remove last 0:).

"Simplified time: " + (hours + ":" + minutes + ":" + seconds + ":").replaceAll("^(0:){1,2}", "");

^(0:){1,2} regex means

  • ^ represents start of string (in our case start of x:x:x: since replaceAll is applied only to that part), it prevents matching 0: in the middle of string if there is no 0: before it,
  • 0: is literal,
  • (0:) is group holding 0: literal, we need it so we could apply quantifiers for that entire literal, not only single character
  • {1,2} quantifier representing "once or twice" (to be more precise in range one till two, since its syntax represents repetition range {nim,max})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download