Constructing a string that does not include integer if it is 0 in Java? -
let's have:
int hours = 0; int minutes = 0; int seconds = 5; system.out.println("simplified time: " + hours + ":" + minutes + ":" + seconds + ":");
it print out:
simplified time: 0:0:5:
does have idea make print out like:
simplified time: 5:
without using if else statements? of course if (hours>0) print out whole print statement if (hours=3) want print out:
simplified time: 3:0:5:
it looks trying remove leading zeroes , :
after them.
if case can apply replaceall(regex,replacement)
x:x:x:
part remove 1 or 2 of 0:
placed @ start (we don't want 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 ofx:x:x:
sincereplaceall
applied part), prevents matching0:
in middle of string if there no0:
before it,0:
literal,(0:)
group holding0:
literal, need apply quantifiers entire literal, not single character{1,2}
quantifier representing "once or twice" (to more precise in range 1 till two, since syntax represents repetition range{nim,max}
)
Comments
Post a Comment