I want to replace 1 by 1Min, 5 by 5Min, 10 by 10Min, 15 by 15Min,60 by 1Hour, 360 by 6Hours etc.
How can I do it in 1 statement.
String str = "15";
String newStr = str.replace("1", "1Min").replace("5", "5Mins").replace("10", "10Mins").replace("15", "15Mins").replace("30", "30Mins").replace("60", "1Hr").replace("120", "2Hrs").replace("240", "4Hrs").replace("480", "8Hrs").replace("720", "12Hrs").replace("1440", "24Hrs");
If I try this, i get '1Min5Mins' because it replaces 1 and then 5.
This could be a stupid question, I can do it with switch or if, else-if. just wondering can this be done in 1 line code.
Thanks
You could try something like this:
String str = "15";
int minutes = Integer.parseInt(str);
if (minutes < 60)
str += "Mins";
else
str = (minutes/60) + "Hrs";
but be aware that Integer.parseInt() will throw an exception if you try to parse anthing else than a number. This can be inaccurate if the hours are not exact (365 will be replaced by 6 hours although it's 6 hours and 5 minutes)
Here's the 1-liner:
str = Integer.parseInt(str) < 60 ? str+"Mins" : (Integer.parseInt(str)/60) + (Integer.parseInt(str)/60 == 1 ? "Hr" : "Hrs");
although this would be more readable with a 2-liner:
int minutes = Integer.parseInt(str);
str = minutes < 60 ? str+"Mins" : (minutes/60) + (minutes/60 == 1 ? "Hr" : "Hrs");
Here is the one-liner for you:
String newStr = str.replaceAll("\\b1\\b", "1Min").replaceAll("\\b5\\b", "5Mins").replace("10", "10Mins").replace("15", "15Mins").replace("30", "30Mins").replace("60", "1Hr").replace("120", "2Hrs").replace("240", "4Hrs").replace("480", "8Hrs").replace("720", "12Hrs").replace("1440", "24Hrs");
With the regex word boundaries. Was too lazy to finish it till the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With