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 of x:x:x: since replaceall applied part), prevents matching 0: in middle of string if there no 0: before it,
  • 0: literal,
  • (0:) group holding 0: 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

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -